C#中扩展方法中的Nullable嵌套类型

Pat*_*ski 0 c# nullable

我试图为一个超酷的扩展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;
}
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点nullables?(比如,不包括int等).

Mat*_*son 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
{
Run Code Online (Sandbox Code Playgroud)

但是,通过使用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;
}
Run Code Online (Sandbox Code Playgroud)

当然,只有当你真的想要它与所有可能的类型一起工作时才这样做,而不仅仅是参考类型.