反序列化后,PropertyChanged事件不再起作用

时间:2016-08-01 11:24:14

标签: c#

我正在使用下面列出的TrulyObservableCollection类。我正在为PropertyChanged事件添加一个事件监听器,并且最初工作正常。但是,只要我序列化和反序列化集合并添加我的事件监听器,就会从下面的单元测试中看到事件不再出现。任何人都可以解释原因吗?

这是班级:

    [Serializable]
public class TrulyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
    [field:NonSerialized]
    public event PropertyChangedEventHandler PropertyChanged;

    public TrulyObservableCollection() { init(); }

    private void init()
    {
        CollectionChanged += TrulyObservableCollection_CollectionChanged;
    }

    void TrulyObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
            foreach (Object item in e.NewItems)
                (item as INotifyPropertyChanged).PropertyChanged += item_PropertyChanged;

        if (e.OldItems != null)
            foreach (Object item in e.OldItems)
                (item as INotifyPropertyChanged).PropertyChanged -= item_PropertyChanged;
    }

    void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(e.PropertyName));
    }
}

这是单元测试。 SIEESerializer.Clone()进行二值化序列化和反序列化。

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        TrulyObservableCollection<SomeData> tt = new TrulyObservableCollection<SomeData>();
        tt.Add(new SomeData());
        tt = SIEESerializer.Clone(tt) as TrulyObservableCollection<SomeData>;
        tt.PropertyChanged += (s, e) =>
        {
            string ttt = ""; // we never get here..
        };
        tt[0].Master = true;
    }
}

[Serializable]
public class SomeData : INotifyPropertyChanged
{
    private bool master;
    public bool Master
    {
        get { return master; }
        set { master = value; SendPropertyChanged(); }
    }

    [field: NonSerialized]
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void SendPropertyChanged([CallerMemberName]string propertyName = null)
    {
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

0 个答案:

没有答案