有没有办法 return null 而不是抛出 NullReferenceException?

Is there a way to return null instead of throwing a NullReferenceException?

我有以下 C# 问题。

考虑函数:

private String getStringFromNullabel()
{
    var nullable = getClass();  // returns some object that could be null
    if( nullable != null)
    {
         return nullable.Text;
    }
    return null;
}

这有效,但它很冗长,我宁愿写这样的东西:

private String getStringFromNullabel()
{
    return NotThrowWrapper(getClass()).Text; 
}

如果 getClass() returns 为空,这将抛出。 因此,我正在寻找一些足够短的语法,使其保持一行,而不是 returns null 而不是抛出异常。

C#里有这样的东西吗?

C#6 之前的版本

private String GetStringFromNullabel()
{
 var nullable = getClass();  // returns some object that could be null
 return nullable  != null ? nullable .Text : null;
}

Post C# 6

private String GetStringFromNullabel()
{
 return getClass()?.Text;
}

请注意,您应该遵循 .NET naming conventions