C# object is not null but (myObject != null) still return false(C# 对象不为空,但 (myObject != null) 仍然返回 false)
问题描述
我需要在对象和 NULL 之间进行比较.当对象不为 NULL 时,我会用一些数据填充它.
I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.
代码如下:
if (region != null)
{
....
}
这是可行的,但是当循环和循环有时区域对象不为空(我可以在调试模式下看到其中的数据).在逐步调试时,它不会进入 IF 语句...当我使用以下表达式进行快速观察时:我看到 (region == null) 返回 false,AND (region != null) 也返回 false...为什么以及如何?
This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when debugging, it doesn't go inside the IF statement... When I do a Quick Watch with these following expression : I see the (region == null) return false, AND (region != null) return false too... why and how?
更新
有人指出该对象被 == 和 != 重载:
Someone point out that the object was == and != overloaded:
public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
public static bool operator !=(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) != 0 || r1.Id != r2.Id);
}
推荐答案
是否为区域对象的类重载了 == 和/或 != 运算符?
Is the == and/or != operator overloaded for the region object's class?
现在您已经发布了重载代码:
Now that you've posted the code for the overloads:
重载应该如下所示(代码取自 Jon Skeet 和 Philip Rieck):
The overloads should probably look like the following (code taken from postings made by Jon Skeet and Philip Rieck):
public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals( r1, r2)) {
// handles if both are null as well as object identity
return true;
}
if ((object)r1 == null || (object)r2 == null)
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
public static bool operator !=(Region r1, Region r2)
{
return !(r1 == r2);
}
这篇关于C# 对象不为空,但 (myObject != null) 仍然返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 对象不为空,但 (myObject != null) 仍然返回 false


- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01