设置 ListView.ItemsSource 时的 StackOverflow

发布于 2024-10-05 23:45:11 字数 651 浏览 5 评论 0原文

所以我有一个简单的结构体Point,其中有两个双精度XY。我计算了一个大约有三百个的数组,并将该数组设置为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦醒时光 2024-10-12 23:45:11

程序尝试再次调用 Equals(object obj),因为您将 obj 作为 object 传递,即使它是 Point< /代码>。所以本质上,过载是一次又一次地调用自己。

当您在内部调用中传递 obj 时,您必须将其强制转换为 Point,因此它将调用 Equals(Point other) 方法:

public override bool Equals(object obj)
{
  if (obj is Point)
    return Equals((Point) obj);

  return false;
}

The program is trying to call Equals(object obj) again because you are passing obj as an object even though it's a Point. So essentially that overload is calling itself again and again.

You have to cast obj to Point when you pass it in the inner call, so it'll call the Equals(Point other) method instead:

public override bool Equals(object obj)
{
  if (obj is Point)
    return Equals((Point) obj);

  return false;
}
多像笑话 2024-10-12 23:45:11

只是一个速记 - 编写 Equals(object) 方法的另一种方法是:(

public override bool Equals(object obj)
{
    return (obj is Point) && Equals((Point)obj);
}

第一组括号实际上不是必需的,但我认为它有助于可读性。)

Just a quickie - an alternative way of writing the Equals(object) method is:

public override bool Equals(object obj)
{
    return (obj is Point) && Equals((Point)obj);
}

(The first set of brackets isn't actually necessary, but I think it helps the readability.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文