我希望能夠使用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;
}
哪個版本的C#/ .net是這個? –
VS2010 .NET 4.0 – slocumro
TrackingRecord是一個自定義類 – slocumro