日期:2014-05-17  浏览次数:20718 次

关于ObservableCollection的一个疑问,大家一起讨论讨论
先上代码,再说疑问^_^

class Program
    {
        static void Main(string[] args)
        {
            ObservableCollection<string> strs = new ObservableCollection<string>();
            strs.Add("123");
            strs.CollectionChanged += new NotifyCollectionChangedEventHandler(strs_CollectionChanged);
            strs.Clear();

            Console.Read();
        }

        private static void strs_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                Console.WriteLine("NEW");
            }

            if (e.OldItems != null)
            {
                Console.WriteLine("OLD");
            }
        }
    }

运行上面的程序,我们可以看到,并没有任何输出。通过调试运行发现,Clear触发了CollectionChanged事件,但是OldItems的值却为null。为什么要这样,难道不应该给出集合中的所有值么?(PS:看来Remove和Clear的实现机制是不一样的)
ObservableCollection C#

------解决方案--------------------
strs.Clear(); 
触发了CollectionChanged事件,说明资源已经被释放了,OldItems当然为NUll了。
如果不想让它为null,就不用strs.Clear(); 这句话,去掉再调试看看。
------解决方案--------------------

clear时会执行下面
protected override void ClearItems()
{
    this.CheckReentrancy();
    base.ClearItems();
    this.OnPropertyChanged("Count");
    this.OnPropertyChanged("Item[]");
    this.OnCollectionReset();
}

this.OnCollectionReset();源码是
private void OnCollectionReset()
{
    this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}

 NotifyCollectionChangedEventArgs的构造中并未对olditems做处理