C# 对象不为 null 但 (myObject != null) 仍然返回 false
- 作者: 竹影风行
- 来源: 51数据库
- 2022-10-20
问题描述
我需要在对象和 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 和 菲利普·里克):
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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
