我有一个如下的扩展方法:
public static T GetValueAs<T, R>(this IDictionary<string, R> dictionary, string fieldName)
where T : R
{
R value;
if (!dictionary.TryGetValue(fieldName, out value))
return default(T);
return (T)value;
}
目前,我可以通过以下方式使用它:
var dictionary = new Dictionary<string, object>();
//...
var list = dictionary.GetValueAs<List<int>, object>("A"); // this may throw ClassCastException - this is expected behavior;
它工作得很好,但是第二个类型参数真的很烦人。是否有可能在 C# 4.0 中重写 GetValueAs 是这样一种方式,该方法仍然适用于不同类型的字符串键字典,并且不需要在调用代码中指定第二个类型参数,即使用
var list = dictionary.GetValueAs<List<int>>("A");
或者至少像 var list = dictionary.GetValueAs<List<int>, ?>("A");
代替 var list = dictionary.GetValueAs<List<int>, object>("A");