带有类型作为键的字典中派生类型参数的函数
我希望能够使用Key作为对象类型将函数存储在字典中。所有的函数都会接受来自同一个基类的对象。我希望能够(基于注册函数)将类转换为DbCommand。我在下面列出了我的代码,看起来是正确的,但语法错误,等等。我想我错过了一些非常简单的东西......任何帮助将不胜感激!带有类型作为键的字典中派生类型参数的函数
private Dictionary<object, Func<TrackingRecord, DbCommand>> conversionFunctions = new Dictionary<object, Func<TrackingRecord, DbCommand>>();
public void RegisterConversionFunction<T>(Func<T, DbCommand> conversionFunction) where T : TrackingRecord
{
conversionFunctions.Add(typeof(T), conversionFunction);
}
public DbCommand GetConverstion<T>(T trackingRecord) where T : TrackingRecord
{
DbCommand command = null;
if (conversionFunctions.ContainsKey(trackingRecord.GetType()))
{
Func<T, DbCommand> conversionFunction;
if (conversionFunctions.TryGetValue(trackingRecord.GetType(), out conversionFunction))
{
command = conversionFunction.Invoke(trackingRecord);
}
}
else
{
command = DefaultConversion(trackingRecord);
}
return command;
}
与你原来的解决方案的问题是,该方法的签名Func<T, DbCommand>
不匹配预期值Func<TrackingRecord, DbCommand>
。为了解决这个问题,因为你知道,T被约束到从TrackingRecord继承,你可以创建一个预期的签名(Func<TrackingRecord, DbCommand>
)相匹配的包装功能部件和铸铁的参数T.
试试这个:
private Dictionary<object, Func<TrackingRecord, DbCommand>> conversionFunctions = new Dictionary<object, Func<TrackingRecord, DbCommand>>();
public void RegisterConversionFunction<T>(Func<T, DbCommand> conversionFunction) where T : TrackingRecord
{
conversionFunctions.Add(typeof(T), tr => conversionFunction((T)tr));
}
public DbCommand GetConverstion<T>(T trackingRecord) where T : TrackingRecord
{
DbCommand command = null;
Func<TrackingRecord, DbCommand> conversionFunction;
if (conversionFunctions.TryGetValue(typeof(T), out conversionFunction))
command = conversionFunction.Invoke(trackingRecord);
else
command = DefaultConversion(trackingRecord);
return command;
}
完美!并感谢您清楚解释! – slocumro
我把它清理了一下,所以它只检查字典一次,并且使用T(这样T的子类无法解析,因为它们应该),并且也使用强大的强制转换而不是“as”强制转换,这样错误更加明显。 –
哪个版本的C#/ .net是这个? –
VS2010 .NET 4.0 – slocumro
TrackingRecord是一个自定义类 – slocumro