繁体   English   中英

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

[英]Nullable nested type in extension method in C#

我正在尝试为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以下where T: class添加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 Type Constraints )。 您想要的是class约束,如下所示:

public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class

这适用于引用类型,这是您真正想要的。 Nullable是否暗示类似int?东西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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM