昨天编程重载“==”时,例程如下:
public class DeviceInfo
{
public override bool Equals(object obj)
{
return this.Device == ((DeviceInfo)obj).Device;
}
public static bool operator ==(DeviceInfo obj1, DeviceInfo obj2)
{
if (obj1 == null) return obj2 == null;
return obj1.Device == obj2.Device;
}
public static bool operator !=(DeviceInfo obj1, DeviceInfo obj2)
{
return !(obj1==obj2);
}
public string Device;//设备名称,关键字
public string IP;//IP地址
//...
}编译无任何问题,但执行时却抛出“Process is terminated due to StackOverflowException.”,经分析,是由于对象为空时,“==”就形成了无结束的递归调用,直至最终堆栈溢出。要解决此问题,必须打破无休止的递归调用,通过调用基类的操作符来解决该问题。
public class DeviceInfo
{
public override bool Equals(object obj)
{
if(! (obj is DeviceInfo)) return false;
DeviceInfo di2 = (DeviceInfo)obj;
return (this.Device.CompareTo(di2.Device)==0);
}
public static bool operator ==(DeviceInfo obj1, DeviceInfo obj2)
{
if ((obj1 as object) == null) return (obj2 as object) == null;//引用基类object的比较操作符
return obj1.Equals(obj2);
}
public static bool operator !=(DeviceInfo obj1, DeviceInfo obj2)
{
return !(obj1==obj2);
}
public string Device;//设备名称,关键字
public string IP;//IP地址
//...
}
编译环境:VS2010(C#)
本文介绍了一个在C#编程过程中遇到的问题:重载“==”操作符时因处理空对象不当导致堆栈溢出,并提供了解决方案。正确的做法是先检查对象是否为null,然后调用基类的比较方法。
1958

被折叠的 条评论
为什么被折叠?



