問題描述
我需要在對象和 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# 對象不為 null 但 (myObject != null) 仍然返回 false的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!