如何在检索时为Dictionary值指定泛型强制转换
本文关键字:泛型 转换 Dictionary 检索 | 更新日期: 2023-09-27 18:04:47
这是我的代码,我写了一个扩展,从字典中获得值与指定的转换
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;
}
错误提示:
错误1类型参数' result '不能与'as'操作符一起使用,因为它没有类类型约束也没有'class'约束
不知道该怎么做
我只需要指定类型,我需要它从方法的返回类型。所以我需要用这个泛型类型强制转换字典值。
请帮帮我!
您需要告诉编译器和api的用户,TResult
将是引用类型的名称,而不是值类型的名称:
public static TResult GetValue<TKey, TValue, TResult>(this Dictionary<TKey, TValue> dictionary, TKey key)
where TResult : class {
...
}
这是使用as TResult
操作符所必需的。如果您希望为值类型提供类似的功能,请添加一个单独的函数,接受值类型的TResult
,并返回Nullable<TResult>
:
public static TResult? GetNullableValue<TKey, TValue, TResult>(this Dictionary<TKey, TValue> dictionary, TKey key)
where TResult : struct {
...
}
as关键字仅对引用类型' nulable有效。
使用强制转换操作符或添加where TResult : class
约束,如果您想要这种限制。
public static TResult GetValue<TKey, TValue, TResult>(this Dictionary<TKey, TValue> dictionary, TKey key)
{
if (!dictionary.ContainsKey(key))
{
return default(TResult);
}
return (TResult)dictionary[key];
}
编译器对TResult
一无所知。尝试添加where TResult: class
:
public static TResult GetValue<TKey, TValue, TResult>(
this Dictionary<TKey, TValue> dictionary, TKey key
) where TResult: class
但是正如**@chglurps*所评论的那样,最好使用TryGetValue
。