【问题标题】:A first chance exception of type 'System.InvalidCastException' occurred in WindowsBase.dllWindowsBase.dll 中出现了“System.InvalidCastException”类型的第一次机会异常
【发布时间】:2014-06-28 10:08:21
【问题描述】:

将 ListBox 的 ItemsSource 绑定到 ObservableCollection<object> 时出现此异常。

集合中混合了 {DependencyPropertyChangedEventArgs, EventEntry}

我偷看了DependencyPropertyChangedEventArgs发现:

public struct DependencyPropertyChangedEventArgs
{
    ...
    public override bool Equals(object obj)
    {
        return this.Equals((DependencyPropertyChangedEventArgs)obj); <- huge cast right here?
    }
}

EventEntry 代码:

public class EventEntry
{
    public EventEntry(string name)
    {
        Name = name;
    }
    public string Name { get; private set; }
}

当我阅读偷看的代码时,它旨在爆炸。

是这样吗?

【问题讨论】:

  • 从 DependencyPropertyChangedEventArgs 派生并覆盖 Equals?或者根本不使用它,而是使用你自己的类?
  • @Clemens 是的,是时候解决问题了!

标签: c# wpf casting listbox equality


【解决方案1】:

确认错误,重现:

[Test]
public void Repro()
{
    var args = new DependencyPropertyChangedEventArgs(UIElement.IsEnabledProperty, false, true);
    Assert.Throws<InvalidCastException>(() => args.Equals(1));
}

Confirmed bug in the implementation: (below code is from reference source)

public override bool Equals(object obj)
{
    return Equals((DependencyPropertyChangedEventArgs)obj);
}

Filed a bug on Connect

【讨论】:

  • 这不是一个答案,更多信息。如果我知道怎么做,应该让它成为维基。
猜你喜欢
  • 2011-09-11
  • 2012-10-29
  • 1970-01-01
  • 2013-11-16
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
相关资源
最近更新 更多