见下面的代码行:
DataTable [] _tables = null;
// Throws System.NullReferenceException
_tables.GetType();
// Throws System.ArgumentNullException
_tables.Count();
在这行代码中我有_tables
引用并尝试访问其系统定义函数GetType()
和Count()
,两者都抛出异常,但为什么.Count()
抛出{{1}因为我们有相同的参考值,System.ArgumentNullException
?
答案 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
上调用一个方法,这个...嗯,不起作用。