软件编程
位置:首页>> 软件编程>> C#编程>> C#集合之可观察集合的用法

C#集合之可观察集合的用法

作者:Ruby_Lu  发布时间:2022-02-16 13:43:13 

标签:C#,集合,可观察

如果需要集合中的元素何时删除或添加的信息,可以使用ObservableCollection<T>类。这个类是为WPF定义的,这样UI就可以得知集合的变化。这个类在程序集WindowsBase中定义,需要引用这个程序集。
ObservableCollection<T>类派生自Collection<T>基类,该基类可用于创建自定义集合,并在内部使用List<T>类。重写基类的虚方法SetItem()和RemoveItem(),以触发CollectionChanged事件。

static void Main()
       {
         var data = new ObservableCollection<string>();
         data.CollectionChanged += Data_CollectionChanged;
         data.Add("One");
         data.Add("Two");
         data.Insert(1, "Three");
         data.Remove("One");

}

static void Data_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
       {
         Console.WriteLine("action: {0}", e.Action.ToString());

if (e.OldItems != null)
         {
           Console.WriteLine("starting index for old item(s): {0}", e.OldStartingIndex);
           Console.WriteLine("old item(s):");
           foreach (var item in e.OldItems)
           {
             Console.WriteLine(item);
           }
         }
         if (e.NewItems != null)
         {
           Console.WriteLine("starting index for new item(s): {0}", e.NewStartingIndex);
           Console.WriteLine("new item(s): ");
           foreach (var item in e.NewItems)
           {
             Console.WriteLine(item);
           }
         }

Console.WriteLine();
       }

来源:https://www.cnblogs.com/afei-24/p/6835420.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com