如果对象为空则抛出异常

throwing an exception if an object is null

我最近发现:

if (Foo() != null)    
   { mymethod(); }

可以改写为

Foo?.mymethod()

下面可以用类似的方式重写吗?

if (Foo == null)
{ throw new Exception()}

我不知道你为什么会..

public Exception GetException(object instance)
{
    return (instance == null) ? new ArgumentNullException() : new ArgumentException();
}

public void Main()
{
    object something = null;
    throw GetException(something);
}

C# 6 中没有类似的时尚语法。

但是,如果您愿意,可以使用扩展方法来简化空检查...

 public static void ThrowIfNull(this object obj)
    {
       if (obj == null)
            throw new Exception();
    }

用法

foo.ThrowIfNull();

或改进它以显示空对象名称。

 public static void ThrowIfNull(this object obj, string objName)
 {
    if (obj == null)
         throw new Exception(string.Format("{0} is null.", objName));
 }

foo.ThrowIfNull("foo");

If null then null; if not then dot

使用 null 条件的代码可以通过在阅读时对自己说出该语句来轻松理解。因此,例如在您的示例中,如果 foo 为 null,则它将 return null。如果它不为空,那么它会 "dot" 然后抛出一个异常,我认为这不是你想要的。

如果您正在寻找 shorthand 处理空值检查的方法,我会推荐 Jon Skeet's answer here and his related blog post 相关主题。

Deborah Kurata referenced this saying in this Pluralsight course 我也推荐。

是的,从 C# 7 开始,您可以使用抛出表达式

var firstName = name ?? throw new ArgumentNullException("Mandatory parameter", nameof(name));

Source

从 .NET 6 框架开始,您可以使用以下 ThrowIfNull 静态方法:

void HelloWorld(string argumentOne)
{
    ArgumentNullException.ThrowIfNull(argumentOne);
    Console.WriteLine($"Hello {argumentOne}");
}