C# C中扩展方法中的可空嵌套类型#
我正在尝试为C# C中扩展方法中的可空嵌套类型#,c#,nullable,C#,Nullable,我正在尝试为IDictionary-GetValue做一个超级酷的扩展,如果没有设置默认值,则默认值为null。下面是我想出的代码(不起作用): publicstatictvalue-GetValue(此IDictionary字典,TKey-key,TValue-defaultValue=null) { t价值; 返回dictionary.TryGetValue(键,输出值) 价值 :默认值; } 如何仅为空值设置此选项?(例如,不包括int等)。使用: publicstatictvalue-
IDictionary
-GetValue
做一个超级酷的扩展,如果没有设置默认值,则默认值为null。下面是我想出的代码(不起作用):
publicstatictvalue-GetValue(此IDictionary字典,TKey-key,TValue-defaultValue=null)
{
t价值;
返回dictionary.TryGetValue(键,输出值)
价值
:默认值;
}
如何仅为空值设置此选项?(例如,不包括int
等)。使用:
publicstatictvalue-GetValue(此IDictionary字典,TKey-key,TValue-defaultValue=null),其中TValue:class
{
t价值;
返回dictionary.TryGetValue(键,输出值)
价值
:默认值;
}
您的意思是仅针对参考类型。添加,其中T:class
,如下所示:
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null)
where TValue: class
{
当然,只有当您确实希望它能够处理所有可能的类型,而不仅仅是引用类型时,才可以这样做。您可以对类型参数()使用约束。这里需要的是类
约束,如下所示:
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class
publicstatictvalue-GetValue(此IDictionary字典,TKey-key,TValue-defaultValue=null),其中TValue:class
这适用于引用类型,这正是您真正想要的。Nullable意味着类似于int?
的东西也可以工作。很好地向OP解释了限制的真正意图nullable
表示它们必须是引用类型。注意:类约束应该在TValue
上,而不是TKey
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null)
where TValue: class
{
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;
}
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class