C# system.stackoverflowexception无法计算表达式,因为当前线程处于堆栈溢出状态
当代码点击此函数时,我得到一个System.StackOverFlowException 其中,stringtype是用户定义的tupe,等于类型库中的函数intC# system.stackoverflowexception无法计算表达式,因为当前线程处于堆栈溢出状态,c#,asp.net,windows-applications,C#,Asp.net,Windows Applications,当代码点击此函数时,我得到一个System.StackOverFlowException 其中,stringtype是用户定义的tupe,等于类型库中的函数int public static bool Equals(StringType leftHand, StringType rightHand) { if (leftHand == rightHand) { return true; } if ((leftHa
public static bool Equals(StringType leftHand, StringType rightHand)
{
if (leftHand == rightHand)
{
return true;
}
if ((leftHand == "0") || (rightHand == "0"))
{
return false;
}
return (leftHand.myValue.Equals(rightHand.myValue) && leftHand.myState.Equals(rightHand.myState));
}
这个
改为
if (object.ReferenceEquals(leftHand, rightHand))
您可能重新定义了=
操作符来调用Equals
我希望您没有从string
创建StringType
的隐式运算符,否则
if ((leftHand == "0") || (rightHand == "0"))
可能会因为同样的原因自称
大概
if ((leftHand.myValue == "0") || (rightHand.myValue == "0"))
会更好。如果您告诉我们您的
StringType
类的重写运算符会更好。谢谢xanatos,当我更改它运行的代码时,没有错误。您的猜测是正确的,我们重新定义了==运算符。我只是想知道当lefthand==right hand时它为什么会出错。因为lefthand==rightHand
调用了重定义的操作符,它又调用了Equals
,它又调用了重定义的操作符等等。如果不使用object.ReferenceEquals
,您可以这样做:((object)leftHand)==((object)righHand)
,因为操作符不能是虚拟的,但我认为使用object.ReferenceEquals
更清楚。请记住,如果创建了不需要执行此检查的struct
s。struct
类型的每个值总是不同的,例如MyFunc(structValue,structValue)
在MyFunc
中,您有两个不同的structValue
副本。您使类递归而没有出路.Equals(StringType,StringType)
会立即调用==(StringType)
,然后会立即调用.Equals(StringType,StringType)
,诸如此类的荒谬行为,直到调用堆栈耗尽空间并抛出StackOverflowException。
if ((leftHand.myValue == "0") || (rightHand.myValue == "0"))