[英]Why do I get a null reference error when using something.Equals(null) in C#
I keep getting a null reference error when I am trying to check if something is null. 当我尝试检查某些内容是否为null时,我不断收到null引用错误。 I have a class called User and I initialize the variable indvUser like so
我有一个名为User的类,并且像这样初始化变量indvUser
User indvUser = api.Users.SearchByExternalId(session.UserInfo.UserId.ToString())
.Users.FirstOrDefault();
Then I want to check if indvUser is null like this 然后我想检查indvUser是否为null
if (indvUser.Equals(null))
{
int a = 1;
}
But I get a null reference error when using Equals(null)
which I don't understand. 但是我使用我不明白的
Equals(null)
时出现空引用错误。 If it actually is null ie there is no value, shouldn't Equals(null)
return true? 如果它实际上是null,即没有值,
Equals(null)
是否不应该返回true?
Since indvUser
is null
, and indvUser.Equals
is an instance method on your User
object (ie, it requires an non-null instance of your object), .NET will throw the error you attempt to use it. 由于
indvUser
为null
,并且indvUser.Equals
是您的User
对象上的实例方法(即,它需要对象的非null实例),因此.NET将抛出您尝试使用它的错误。
For something like this, you could use this: 对于这样的事情,您可以使用以下代码:
Object.ReferenceEquals(indvUser, null)
Or simply: 或者简单地:
indvUser == null
Since neither of these approaches actually attempt to access methods or properties on the indvUser
object itself, you should be safe from NullReferenceExceptions
由于这两种方法均未尝试访问
indvUser
对象本身的方法或属性,因此应避免使用NullReferenceExceptions
In line: 排队:
indvUser.Equals(null)
if indvUser
is null, how Equals
method could be called on it? 如果
indvUser
为 null,如何在其上调用Equals
方法? It simply can be seen as: 它可以简单地看作是:
null.Equals(null)
You should compare it as indvUser == null
or object.ReferenceEquals(indvUser, null)
您应该将其与
indvUser == null
或object.ReferenceEquals(indvUser, null)
Object.Equals is a method which is not static. Object.Equals是一个不是静态的方法。 In order to call the Equals method, you must have an instance of the class.
为了调用Equals方法,您必须具有该类的实例。
如果indUser == null
,则将执行null.Equals(null)
,这将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.