参考类型中的C#HasValue

时间:2014-05-30 08:03:49

标签: c# reference nullable reference-type

是否可以在引用类型上使用Nullable<>.HasValue

假设我们从值类型中得到了这个例子:

int? a = GetNullOrValue(); // completely randomly gets random number or null
if (a.HasValue) return 0;

我想要完成的是:

class Foo 
{
    public string Bar { get; set; }
}

Foo foo = GetNullOrFoo(); // completely randomly gets Foo ref. or null

if (foo.HasValue) return foo.Bar; // of course this will throw NullReferenceException if foo is null

为了更好的可读性,我希望实现这一点,因为我更喜欢“单词内容”,而不是“符号内容”(x.HasValue而不是x != null)。

1 个答案:

答案 0 :(得分:5)

您可以编写扩展方法。

public static class Extension
{
    public static bool HasValue<T>(this T self) where T : class
    {
        return self != null;
    }
}

然后你可以使用

if (foo.HasValue()) return foo.Bar; 

但是,老实说x != null很简单,这种扩展方法会让维护者感到困惑,我不会推荐它。

如果您打算使用此方法,请进一步阅读。这只有在没有名为HasValue的实例方法时才会起作用,如果有任何实例方法将被调用,而不是扩展方法。因此,它将导致NullReferenceException。不要对结果感到惊讶。所以在你这样做之前要三思而行。


  

始终将代码视为最终维护代码的人员   暴力的精神病患者谁知道你住在哪里。

来自Code For The Maintainer