作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有如下的扩展方法:
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");
最佳答案
只要你只在对象的字典上使用它,你就可以将 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;
}
但这可能不是您想要的。请注意,C# 版本 4 doesn't solve your problem要么。
关于c# - 如何部分指定泛型方法类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2584737/
我是一名优秀的程序员,十分优秀!