C#中扩展方法中的嵌套类型可为null
本文关键字:null 嵌套类型 扩展 方法 | 更新日期: 2023-09-27 17:51:04
我正在尝试为IDictionary
-GetValue
制作一个超级酷的扩展,如果不设置默认值,则该扩展为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
等(。
您的意思是仅针对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;
}
当然,只有当你真的想让它与所有可能的类型一起工作,而不仅仅是与引用类型一起工作时,才可以这样做。
您可以对类型参数使用约束(MSDN类型约束(。这里你想要的是class
约束,就像这样:
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class
这适用于引用类型,这正是您真正想要的。可以为null意味着类似int?
的东西也可以工作。
使用类约束:
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;
}