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

http://blog.csdn.net/wonsoft/article/details/6610245


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

[csharp] view plain copy
  1. public class DeviceInfo  
  2. {  
  3.     public override bool Equals(object obj)  
  4.     {  
  5.         return this.Device == ((DeviceInfo)obj).Device;  
  6.     }  
  7.   
  8.     public static bool operator ==(DeviceInfo obj1, DeviceInfo obj2)  
  9.     {  
  10.        if (obj1 == nullreturn obj2 == null;  
  11.         
  12.        return obj1.Device == obj2.Device;   
  13.     }  
  14.   
  15.     public static bool operator !=(DeviceInfo obj1, DeviceInfo obj2)  
  16.     {  
  17.        return !(obj1==obj2);  
  18.     }  
  19.   
  20.     public string Device;//设备名称,关键字  
  21.     public string IP;//IP地址  
  22.     //...      
  23. }  

编译无任何问题,但执行时却抛出“Process is terminated due to StackOverflowException.”,经分析,是由于对象为空时,“==”就形成了无结束的递归调用,直至最终堆栈溢出。要解决此问题,必须打破无休止的递归调用,通过调用基类的操作符来解决该问题。

[csharp] view plain copy
  1. public class DeviceInfo  
  2. {  
  3.     public override bool Equals(object obj)  
  4.     {  
  5.          if(! (obj is DeviceInfo)) return false;  
  6.   
  7.          DeviceInfo di2 = (DeviceInfo)obj;  
  8.          return (this.Device.CompareTo(di2.Device)==0);  
  9.     }  
  10.           
  11.     public static bool operator ==(DeviceInfo obj1, DeviceInfo obj2)  
  12.     {  
  13.          if ((obj1  as object) == nullreturn (obj2 as object) == null;//引用基类object的比较操作符  
  14.   
  15.          return obj1.Equals(obj2);  
  16.     }  
  17.   
  18.     public static bool operator !=(DeviceInfo obj1, DeviceInfo obj2)  
  19.     {  
  20.        return !(obj1==obj2);  
  21.     }  
  22.   
  23.     public string Device;//设备名称,关键字  
  24.     public string IP;//IP地址  
  25.     //...      
  26. }  


编译环境:VS2010(C#)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值