【发布时间】:2011-02-04 19:09:27
【问题描述】:
我有如下扩展方法:
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");
【问题讨论】:
-
那么,基本上你要做的是从
dictionary推断R的类型,而不是指定它? -
是的,这就是我想要的。
标签: c# generics .net-4.0 extension-methods covariance