参考类型中的C#HasValue

YOh*_*han 1 c# nullable reference reference-type

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

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

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

我想要完成的是:

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
Run Code Online (Sandbox Code Playgroud)

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

Sri*_*vel 5

您可以编写扩展方法.

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

然后你可以使用

if (foo.HasValue()) return foo.Bar; 
Run Code Online (Sandbox Code Playgroud)

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

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


总是编码好像最终维护你的代码的人是一个知道你住在哪里的暴力精神病患者.

引用代码为维护者

  • 我打赌,你可能觉得它现在可读.但是,将来你会意识到你是多么愚蠢...... :)当有一个名为`HasValue`的实例方法时,它会使情况更糟.在这种情况下,您的扩展名将不会被调用并导致`NullReferenceException`.所以它也可能让你感到困惑. (2认同)