设置 ListView.ItemsSource 时的 StackOverflow
所以我有一个简单的结构体Point
,其中有两个双精度X
和Y
。我计算了一个大约有三百个的数组,并将该数组设置为 WPF 中 ListView 的 ItemsSource。该调用最终会抛出 StackOverflowException。
调试器在我的结构中的 Equals
方法的开头处中断,我是这样实现的(如果重要的话):
public override bool Equals(object obj)
{
if (obj is Point)
return Equals(obj);
return false;
}
public bool Equals(Point other) // Implement IEquatable<T>
{
return this.x == other.x && this.y == other.y;
}
如果我将其更改为:
public override bool Equals(object obj)
{
return false;
}
什么也没有发生,并且显示数字。我真的不知道我在这里做错了什么,所以我不知道如何解决这个问题。有什么指点吗?
So I have a simple struct Point
with two doubles X
and Y
. I calculate an array of about three hundred of them and set that array as ItemsSource for a ListView in WPF. That call eventually throws a StackOverflowException
.
De debugger breaks at the beginning of the Equals
method in my struct, which I implemented like so (should it matter):
public override bool Equals(object obj)
{
if (obj is Point)
return Equals(obj);
return false;
}
public bool Equals(Point other) // Implement IEquatable<T>
{
return this.x == other.x && this.y == other.y;
}
If I change that to this:
public override bool Equals(object obj)
{
return false;
}
Nothing happens and the numbers get displayed. I really don't know what I did wrong here, so I don't know how to fix this. Any pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
程序尝试再次调用
Equals(object obj)
,因为您将obj
作为object
传递,即使它是Point< /代码>。所以本质上,过载是一次又一次地调用自己。
当您在内部调用中传递
obj
时,您必须将其强制转换为Point
,因此它将调用Equals(Point other)
方法:The program is trying to call
Equals(object obj)
again because you are passingobj
as anobject
even though it's aPoint
. So essentially that overload is calling itself again and again.You have to cast
obj
toPoint
when you pass it in the inner call, so it'll call theEquals(Point other)
method instead:只是一个速记 - 编写 Equals(object) 方法的另一种方法是:(
第一组括号实际上不是必需的,但我认为它有助于可读性。)
Just a quickie - an alternative way of writing the Equals(object) method is:
(The first set of brackets isn't actually necessary, but I think it helps the readability.)