我正在尝试为IDictionary
- GetValue
制作超酷的扩展程序,默认值为null(如果未设置),则为null。这是我提出的代码(不起作用):
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null)
{
TValue value;
return dictionary.TryGetValue(key, out value)
? value
: defaultValue;
}
如何仅为nullables
制作此内容? (比如,不包括int
等)。
答案 0 :(得分:7)
您的意思是仅reference types
。按如下方式添加where T: class
:
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null)
where TValue: class
{
但是,通过使用default(TValue)
指定默认值,您也可以使用值类型:
public static TValue GetValue<TKey, TValue>(this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = default(TValue))
{
TValue value;
return dictionary.TryGetValue(key, out value)
? value
: defaultValue;
}
当然,只有在你真正希望它能够处理所有可能的类型时才这样做,而不仅仅是使用引用类型。
答案 1 :(得分:2)
您可以对类型参数使用约束(MSDN Type Constraints)。你想要的是class
约束,如下所示:
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class
这适用于参考类型,这是您真正想要的。 Nullable意味着像int?
这样的东西。
答案 2 :(得分:0)
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class
{
TValue value;
return dictionary.TryGetValue(key, out value)
? value
: defaultValue;
}