问题描述
我需要做的对象和NULL之间的comparaison。当对象不为空我用一些数据填充它。
下面是code:
如果(区!= NULL)
{
....
}
这是工作,但循环和循环某个区域对象时不为空(我可以看到在调试模式里面的数据)。在一步一步的调试时,它不走的IF语句中......当我做一个快速监视这些下列前pression:我看(区== NULL)返回false,AND(区域!= NULL)返回false太... 为什么和如何?
更新
有人指出,目标是==和=重载:
公共静态布尔运算符==(地区R1,R2区)
{
如果(object.ReferenceEquals(R1,NULL))
{
返回false;
}
如果(object.ReferenceEquals(R2,NULL))
{
返回false;
} 回报(r1.Cmr.CompareTo(r2.Cmr)== 0安培;&安培; r1.Id == r2.Id);
}
公共静态布尔运算符!=(区域R1,R2区)
{
如果(object.ReferenceEquals(R1,NULL))
{
返回false;
}
如果(object.ReferenceEquals(R2,NULL))
{
返回false;
}
回报(r1.Cmr.CompareTo(r2.Cmr)= 0 || r1.Id = r2.Id!);
}
是==和/或!=运算符重载该区域对象的类?
现在,您已经张贴的code为重载:
的重载或许应该看起来像由Jon飞碟和Philip里克):
公共静态布尔运算符==(地区R1,R2区)
{
如果(object.ReferenceEquals(R1,R2)){
//处理,如果都为null,以及对象标识
返回true;
} 如果((对象),R1 == NULL ||(对象)R2 == NULL)
{
返回false;
} 回报(r1.Cmr.CompareTo(r2.Cmr)== 0安培;&安培; r1.Id == r2.Id);
}公共静态布尔运算符!=(区域R1,R2区)
{
返回(R1 R2 ==)!;
}
I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.
Here is the code :
if (region != null)
{
....
}
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?
Update
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:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!