我正在阅读 this post回答者提到他更喜欢 ArgumentNullException
而不是 NullReferenceException
。
MSDN提到 NullReferenceException
:
The exception that is thrown when there is an attempt to dereference a null object reference.
关于 ArgumentNullException
they说:
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
回答者似乎说你可以使用任何一个。
有什么理由或任何情况我应该选择一个而不是另一个吗?
附言
我知道这个问题可能是基于意见的。 我想要事实、背景和情况。我对个人偏好不感兴趣。
最佳答案
如果您在代码中明确抛出异常,则应选择 ArgumentNullException
。
NullReferenceException
在取消引用空引用/指针时由 CLR 自动抛出:
unsafe
{
int* ptr = null; // Null pointer.
int val = *ptr; // NullReferenceException thrown.
}
这最常发生在对空引用调用方法或属性时:
string text = null;
string substring = text.Substring(0, 2); // NullReferenceException thrown.
在大多数情况下,不应在代码中显式抛出 NullReferenceException
。
ArgumentNullException
用于检查空引用作为参数传递的情况,通常是为了防止 NullReferenceException
。
static string FirstTwo(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return value.Substring(0, 2); // without the original check, this line would throw a NullReferenceException if value were null.
}
这个检查的目的是为了让调用者清楚的知道null
是通过的,null
是不允许的。否则,如果您只是让 NullReferenceException
被抛出,调用者只会看到
Object reference not set to an instance of an object
这不像这样有意义(使用支票时):
Value cannot be null. Parameter name: value
关于c# - NullReferenceException 与 ArgumentNullException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39520241/