問(wèn)題描述
我需要在對(duì)象和 NULL 之間進(jìn)行比較.當(dāng)對(duì)象不是 NULL 時(shí),我用一些數(shù)據(jù)填充它.
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)
{
....
}
這是有效的,但有時(shí)在循環(huán)和循環(huán)時(shí),區(qū)域?qū)ο蟛粸榭?我可以在調(diào)試模式下看到其中的數(shù)據(jù)).在調(diào)試時(shí)的逐步調(diào)試中,它不會(huì)進(jìn)入 IF 語(yǔ)句......當(dāng)我使用以下表達(dá)式進(jìn)行快速觀察時(shí):我看到 (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?
更新
有人指出對(duì)象是 == 和 != 重載:
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);
}
推薦答案
== 和/或 != 運(yùn)算符是否為區(qū)域?qū)ο蟮念愔剌d?
Is the == and/or != operator overloaded for the region object's class?
既然您已經(jīng)發(fā)布了重載的代碼:
Now that you've posted the code for the overloads:
重載應(yīng)該如下所示(代碼取自 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);
}
這篇關(guān)于C# 對(duì)象不為 null 但 (myObject != null) 仍然返回 false的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!