这是我作为扩展编写的代码,用于从具有指定转换的字典中获取值
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/