C#重载操作符“==”执行时引发“Process is terminated due to StackOverflowException.”的解决办法

 昨天编程重载“==”时,例程如下:

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#)


 

你可能感兴趣的:(object,String,C#,null,equals,Class)