C#重载操作符“==”执行时引发“Process is terminated due to StackOverflowException.”的解决办法
2011-07-16 10:56
691 查看
昨天编程重载“==”时,例程如下:
编译环境:VS2010(C#)
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#重载操作符“==”执行时引发“Process is terminated due to StackOverflowException.”的解决办法
- .NET程序报错:Process is terminated due to StackOverflowException.
- 解决办法:Access restriction: The type JPEGImageEncoder is not accessible due to restriction
- 解决办法:Access restriction: The type JPEGImageEncoder is not accessible due to restriction
- Unable to execute dex: java.nio.BufferOverflowException 解决办法
- [Unity][C#][File]File无法新建文件UnauthorizedAccessException,File.Create is denied的解决办法
- C#中异常:“The type initializer to throw an exception(类型初始值设定项引发异常)”的简单分析与解决方法
- 关于dubbo调度时出现Request processing failed; nested exception is com.alibaba.dubbo.rpc.RpcException: Failed to invoke the method insertTestTb in the service cn.cuibusi.core.service.TestTbService.的解决办法
- Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier解决办法
- Unable to execute dex: java.nio.BufferOverflowException.解决办法
- your project contains error(s),..Unable to execute dex: java.nio.BufferOverflowException解决办法
- Jboss启动时,StandardServletAsyncWebRequest due to exception异常的解决办法
- C#中异常:“The type initializer to throw an exception(类型初始值设定项引发异常)”的简单分析与解决方法
- 解决办法:Access restriction: The type JPEGImageEncoder is not accessible due to restriction .
- 解决办法:Access restriction: The type JPEGImageEncoder is not accessible due to restriction on required
- Unable to execute dex: java.nio.BufferOverflowException.解决办法
- Unable to execute dex: java.nio.BufferOverflowException.解决办法
- Unable to execute dex: java.nio.BufferOverflowException.解决办法
- 解决办法:Access restriction: The type JPEGImageEncoder is not accessible due to restriction
- Unable to execute dex: java.nio.BufferOverflowException.解决办法