C# - 使用Lambda的System.StackOverflowException

Bud*_*Joe 7 .net c# stack-overflow sorting lambda

在什么情况下,这个代码会出现System.StackOverflowException错误?

Accounts.Sort((x, y) => string.Compare(x.AccountId, y.AccountId));
Run Code Online (Sandbox Code Playgroud)

更新:
该属性写为:

    public string AccountId
    {
        get { return _accountId; }
        set { _accountId = value; }
    }
Run Code Online (Sandbox Code Playgroud)

没什么特别的.排序也不会被覆盖.

Hen*_*nri 5

查看callstack,您将看到一遍又一遍地执行哪个函数.如果这不可能(例如,因为它在生产环境中运行),请提供更多信息.

关于被调用的属性调用什么,调用此函数的位置等


Mar*_*ell 5

如果AccountId做一些非平凡的事情(除了访问本地字段之外的任何事情)那么这是最可能的赌注.

一个有趣的事实是技术上 Sort要求排序是可传递的,字符串比较并不总是传递的!但这很少会导致堆栈溢出(除非该Sort方法使用某种FP方法); 它可能导致它永远运行,但我相信内置类型甚至覆盖了它们(它们检查理论上的最大游程长度和中止,IIRC).

我会看AccountId; 如果它做了"聪明"的事情(比如从父集合中延迟加载某些值),那么错误就在于"聪明".

  • 传递错误似乎在.Net 4.0中得到修复 (6认同)

jdm*_*hal 5

所以我遇到了一个棘手的情况,我在比较方法中得到了StackOverflow异常.

我的比较方法:

public bool Equals(Type rhs)
{
    if (rhs == null) return false;
    if (this == rhs) return true;

    return this.randomField.Equals(rhs.randomField);
}
Run Code Online (Sandbox Code Playgroud)

我的运营商:

public static bool operator ==(Type lhs, Type rhs)
{
    if (lhs == null)
        return (rhs == null);
    else
        return lhs.Equals(rhs);
}
Run Code Online (Sandbox Code Playgroud)

所以,发生的是==运算符调用Equals方法,然后在运行该行时调用==运算符this == rhs.解决方案是将线路转换为Object.ReferenceEquals(this, rhs).