且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#:用于验证"***实践;这&​​QUOT;论点扩展方法

更新时间:2022-12-08 12:14:43

您应该抛出一个ArgumentNullException。你试图做参数验证,因此应该抛出调谐参数验证异常。 NullReferenceException异常不是一个参数验证例外。这是一个运行时错误。

You should throw an ArgumentNullException. You're attempting to do argument validation and hence should throw an exception tuned to argument validation. NullReferenceException is not an argument validation exception. It's a runtime error.

不要忘了,扩展方法是引擎盖下只是静态方法,可以称为这样的。虽然它可能表面上看起来有道理扔在一个扩展方法一个NullReferenceException,这没有任何意义,为静态方法做到这一点。这是无法确定该方法的调用约定,因而ArgumentException的是更好的选择。

Don't forget, extension methods are just static methods under the hood and can be called as such. While it may seem on the surface to make sense to throw a NullReferenceException on an extension method, it does not make sense to do so for a static method. It's not possible to determine the calling convention in the method and thus ArgumentException is the better choice.

此外,你应该永远不明确抛出一个NullReferenceException。这应该只由CLR被抛出。有明确的时候抛出异常的,通常只能由CLR抛出发生细微的差别。

Also, you should not ever explicitly throw a NullReferenceException. This should only be thrown by the CLR. There are subtle differences that occur when explicitly throwing exceptions that are normally only thrown by the CLR.

这也接近以下

  • ArgumentNullException or NullReferenceException from extension method?