假设我有一个看起来像这样的函数:
public void DoSomething(Action<object> something)
{
something(getObject());
}
如果something
为 null,则此代码将引发 NullReferenceException。
但是,something == null
不会编译,那么我如何测试something
以确定它是否为空?
假设我有一个看起来像这样的函数:
public void DoSomething(Action<object> something)
{
something(getObject());
}
如果something
为 null,则此代码将引发 NullReferenceException。
但是,something == null
不会编译,那么我如何测试something
以确定它是否为空?
您应该能够直接针对 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
}
你有没有尝试过:
if(something == null) throw new ArgumentNullException("something");
我看不出这不能编译的原因?
if(something == null)
{
throw new ArgumentNullException("something");
}
作为您方法的第一块,这应该很有效。
你是如何写出你的“something == null”语句的?下面是为我编译的,我认为您可以对其进行一些调整以具有适当的 if/else 条件。
public void DoSomething(Action<object> something)
{
if (something != null)
{
something(getObject());
}
}