如何测试Action <...>是否为空?

Dan*_*don 3 .net c# null functional-programming nullreferenceexception

假设我有一个如下所示的函数:

public void DoSomething(Action<object> something)
{
    something(getObject());
}
Run Code Online (Sandbox Code Playgroud)

如果something为null,则此代码将引发NullReferenceException.

但是,something == null不会编译,所以如何测试something以确定它是否为空?

Ree*_*sey 8

您应该能够直接测试null.编译好:

public void DoSomething(Action<object> something)
{
    if (something == null) // Note that there are no () on something
    {
        throw new ArgumentNullException("something");
    }

    something(GetObject()); // Assumes `GetObject()` method is available on class, etc
}
Run Code Online (Sandbox Code Playgroud)