这是一个现成的想法:
帐户是否声明为List<Account>?
我想知道Accounts 是否是一个声明为List<Account> 以外的属性——例如,IList<Account>——并且你在某处有一个静态帮助器类和一个Sort 扩展方法没有正确实施。当传入的参数是 List<T> 时,这可能会尝试利用 List<T>.Sort 方法,但这样做时不会执行必要的转换为 List<T>,从而保证 StackOverflowException。
我的意思是这个。假设Account 是某个类的属性,看起来像这样:
public class AccountManager
{
public IList<Account> Accounts { get; private set; }
public AccountManager()
{
// here in the constructor, Accounts is SET to a List<Account>;
// however, code that interacts with the Accounts property will
// only know that it's interacting with something that implements
// IList<Account>
Accounts = new List<Account>();
}
}
然后假设在其他地方你有这个带有Sort 扩展方法的静态类:
public static class ListHelper
{
public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
{
// programmer tries to use the built-in sort, if possible
if (list is List<T>)
{
// only problem is, list is here still typed as IList<T>,
// so this line will result in infinite recursion
list.Sort(comparison);
// the CORRECT way to have done this would've been:
// ((List<T>)list).Sort(comparison);
return;
}
else
{
list.CustomSort(comparison);
return;
}
}
private static void CustomSort<T>(this IList<T> list, Comparison<T> comparison)
{
// some custom implementation
}
}
在这种情况下,您发布的代码会抛出 StackOverflowException。
原答案:
也许Accounts 是一个自定义集合类的对象,其Sort 方法会调用自身?
public class AccountCollection : IEnumerable<Account> {
// ...
public void Sort(Comparison<Account> comparison) {
Sort(comparison); // infinite recursion
}
// ...
}
也许AccountId 属性会调用自己?
public class Account {
// ...
public string AccountId {
get { return AccountId; } // infinite recursion
}
// ...
}