C#集合之可观察集合的用法
作者:Ruby_Lu 时间:2022-02-16 13:43:13
如果需要集合中的元素何时删除或添加的信息,可以使用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
标签:C#,集合,可观察
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android编程使用Service实现Notification定时发送功能示例
2023-03-12 09:54:44
java中的SpringBoot框架
2022-02-10 16:50:05
C#实现围棋游戏
2022-04-20 11:08:57
![](https://img.aspxhome.com/file/2023/0/96400_0s.jpg)
java多线程CyclicBarrier的使用案例,让线程起步走
2023-05-20 16:22:22
IDEA 中使用 Hudi的示例代码
2021-08-27 21:51:04
![](https://img.aspxhome.com/file/2023/6/76236_0s.jpg)
Android ItemDecoration 实现分组索引列表的示例代码
2022-02-10 20:22:12
![](https://img.aspxhome.com/file/2023/1/98661_0s.gif)
C#的String和StringBuilder详解
2022-06-21 09:51:31
![](https://img.aspxhome.com/file/2023/4/98174_0s.gif)
java使用listIterator逆序arraylist示例分享
2022-06-16 05:33:10
![](https://img.aspxhome.com/file/2023/4/104004_0s.jpg)
SpringBoot上传图片到指定位置并返回URL的实现
2023-08-13 14:02:52
![](https://img.aspxhome.com/file/2023/4/88064_0s.jpg)
聊聊Redis二进制数组Bitmap
2021-07-26 11:51:57
SpringBoot 过滤器与拦截器实例演示
2021-08-26 08:33:23
![](https://img.aspxhome.com/file/2023/9/84639_0s.png)
Java线程同步的四种方式详解
2021-09-02 19:57:36
![](https://img.aspxhome.com/file/2023/9/60909_0s.png)
Java编程关于子类重写父类方法问题的理解
2022-05-25 05:00:32
![](https://img.aspxhome.com/file/2023/7/71837_0s.jpg)
Android Selector和Shape的使用方法
2022-08-05 23:48:38
![](https://img.aspxhome.com/file/2023/7/106057_0s.gif)
C#基础:Dispose()、Close()、Finalize()的区别详解
2021-10-22 19:20:23
java睡眠排序算法示例实现
2022-04-01 00:13:32
![](https://img.aspxhome.com/file/2023/2/69882_0s.png)
C#策略模式(Strategy Pattern)实例教程
2022-11-29 07:35:07
![](https://img.aspxhome.com/file/2023/5/71075_0s.png)
Java SE之了解泛型
2022-08-10 08:42:54
![](https://img.aspxhome.com/file/2023/8/84788_0s.jpg)
关于java 图形验证码的解决方法
2023-08-09 15:21:19
Android 获得View宽高的几种方式总结
2021-11-12 05:06:49
![](https://img.aspxhome.com/file/2023/6/101846_0s.png)