为什么ArgumentNullException?为什么不System.NullReferenceException?

时间:2013-08-09 11:36:41

标签: c# nullreferenceexception argumentexception

见下面的代码行:

DataTable [] _tables = null;

// Throws System.NullReferenceException
_tables.GetType();

// Throws System.ArgumentNullException
_tables.Count();

在这行代码中我有_tables引用并尝试访问其系统定义函数GetType()Count(),两者都抛出异常,但为什么.Count()抛出{{1}因为我们有相同的参考值,System.ArgumentNullException

4 个答案:

答案 0 :(得分:20)

Count()IEnumerable<T>上的extension method,在System.Linq.Enumerable中声明 - 因此您实际致电:

Enumerable.Count(_tables);

...所以_tables 一个方法参数,并且异常告诉你这是有意义的。当您致电_tables时,您实际上并未取消引用Count()变量,而当您致电GetType

答案 1 :(得分:7)

因为Count这里是对_tables作为参数的扩展方法的调用 - 实际上是:

System.Linq.Enumerable.Count(_tables);

如果您不想使用扩展方法:请使用_tables.Length

答案 2 :(得分:4)

Count()是一个扩展方法(因此,如果传入的值为null且null为非法,则应抛出ArgumentNullException),而不是对象实例上的方法,即Count定义为public static int Count<T>(this IEnumerable<T> source)

答案 3 :(得分:4)

因为它是扩展方法,而不是实例方法。

由于它已编译为Enumerable.Count(_tables),因此不适用于NullReferenceException,因此只会引发ArgumentNullException。但是,GetType是一个实例方法,所以你试图在null上调用一个方法,这个...嗯,不起作用。