c# - 如何在检索时为字典值指定通用类型转换

标签 c# dictionary

这是我作为扩展编写的代码,用于从具有指定转换的字典中获取值

public static TResult GetValue<TKey, TValue, TResult>(this Dictionary<TKey, TValue> dictionary, TKey key)
{
    if (!dictionary.ContainsKey(key))
    {
        return default(TResult);
    }

    return dictionary[key] as TResult;
}

错误指出,

Error 1 The type parameter 'TResult' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint

无法找到一种方法来做到这一点。

我只需要指定我需要的类型作为方法的返回类型。所以我需要用这个通用类型转换字典值。

请帮帮我!

提前致谢。

最佳答案

您需要告诉编译器和 API 的用户 TResult将是引用类型的名称,而不是值类型的名称:

public static TResult GetValue<TKey, TValue, TResult>(this Dictionary<TKey, TValue> dictionary, TKey key)
    where TResult : class {
    ...
}

这是让您使用 as TResult 所必需的运算符(operator)。如果您希望为值类型提供类似的功能,请添加一个单独的函数,该函数采用 TResult值类型,返回Nullable<TResult>相反:

public static TResult? GetNullableValue<TKey, TValue, TResult>(this Dictionary<TKey, TValue> dictionary, TKey key)
    where TResult : struct {
    ...
}

关于c# - 如何在检索时为字典值指定通用类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636223/

相关文章:

ios - 如何找到 map 中某个点的角度方向(相对于北方)

c# - 正则表达式反对 XPath 之后的标记?

c# - EF5;将 20100326 之类的字符串转换为 2010/03/26

python - 来自键路径的嵌套字典值

c# - C#中字典的内存使用

javascript - Html5 Canvas map 应用程序/每个图 block 的 Canvas 与一个图层的单个 Canvas

python - 将列表中的字典键从 unicode 编码为 ascii

C# 使用 LINQ 连接两个数据表

c# - 使用列在 WPF ListView 中添加项目

c# - 我可以使用什么技术为我的 C# 应用程序编写一个 View ?