gpt4 book ai didi

c# - 如何部分指定泛型方法类型参数

转载 作者:太空狗 更新时间:2023-10-29 23:48:41 26 4
gpt4 key购买 nike

我有如下的扩展方法:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com