DNN*_*NNX 5 c# generics extension-methods .net-4.0 covariance
我有如下扩展方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
目前,我可以通过以下方式使用它:
var dictionary = new Dictionary<string, object>();
//...
var list = dictionary.GetValueAs<List<int>, object>("A"); // this may throw ClassCastException - this is expected behavior;
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但是第二种类型的参数确实很烦人。在C#4.0中是否可以重写GetValueAs这样一种方法,使得该方法仍将适用于不同类型的字符串键字典,并且无需在调用代码中指定第二种类型的参数,即use
var list = dictionary.GetValueAs<List<int>>("A");
Run Code Online (Sandbox Code Playgroud) 或至少像 var list = dictionary.GetValueAs<List<int>, ?>("A");
Run Code Online (Sandbox Code Playgroud) 代替 var list = dictionary.GetValueAs<List<int>, object>("A");
Run Code Online (Sandbox Code Playgroud)
只要您仅在对象字典上使用它,您就可以将 T 约束为引用类型以使强制转换有效:
public static T GetValueAs<T>(this IDictionary<string, object> dictionary, string fieldName)
where T : class {
object value;
if (!dictionary.TryGetValue(fieldName, out value))
return default(T);
return (T)value;
}
Run Code Online (Sandbox Code Playgroud)
但这可能不是您想要的。请注意,C# 版本 4也不能解决您的问题。
| 归档时间: |
|
| 查看次数: |
2548 次 |
| 最近记录: |