在null实例(扩展方法不允许)的情况下调用扩展方法时,您认为是最好的异常类型是什么?由于扩展方法只不过是静态方法,你可以说它应该是ArgumentNullException,但另一方面它们像实例方法一样使用,因此使用NullReferenceException可能更自然.我们来看下面的例子:
public static string ToInvariantString(this IFormattable value, string format)
{
return value.ToString(format, CultureInfo.InvariantCulture);
}
Run Code Online (Sandbox Code Playgroud)
这样,如果value参数为null,则抛出NullReferenceException.
另一个例子是:
public static string ToInvariantString(this IFormattable value, string format)
{
if (value == null) throw new ArgumentNullException("value");
return value.ToString(format, CultureInfo.InvariantCulture);
}
Run Code Online (Sandbox Code Playgroud)
编辑: 在一些答案中,你已经指出扩展方法可以像静态方法一样调用,在这种情况下,空引用异常会出错,这是一个很好的观点,实际上是我关注的一个问题,不知道为什么我忘了首先在问题中提到这一点.
有人还指出抛出NullReferenceException是错误的,是的,确实如此.这就是为什么我不扔它,我只是让它发生(让CLR抛出它)不守护方法.
我认为我赞成ArgumentNullException(这是我到目前为止所使用的)但我仍然认为至少有空间来反对NullReferenceException,因为在大多数将要使用该方法的地方看起来更自然.
假设我有一个Foo具有复杂属性的类Bar.然后,假设我在其他类中有类似以下的方法:
public void DoSomething(Foo foo)
{
if (foo == null)
throw new ArgumentNullException("foo");
if (foo.Bar == null)
throw new ArgumentNullException("bar");
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下使用是否ArgumentNullException适当,严格来说,foo.Bar在这种情况下不是一个论据?我已经阅读并且可以理解,NullReferenceException手动抛出是不合适的.这告诉我我需要抽象吗?
public void DoSomething(Foo foo)
{
if (foo == null)
throw new ArgumentNullException("foo");
DoSomethingElse(foo.Bar);
}
private void DoSomethingElse(Bar bar)
{
if (bar == null)
throw new ArgumentNullException("bar");
}
Run Code Online (Sandbox Code Playgroud)
我的第一个代码片段是"正确"用法ArgumentNullException吗?处理这种情况的传统方法是什么?
谢谢.