Collection 的一个坑

时间:2023-03-09 05:55:44
Collection<T> 的一个坑

当前所在的公司偏好使用 Collection<T>(System.Collections.ObjectModel), 这货比起List<T>不仅少了很多实用方法, 而且还有一个坑
它的一个构造函数支持传入IList实例
Collection<T>(IList<T>)
使用这个构造函数创建出来的Collection实例, 居然要影响原来的IList实例
MSDN的描述为: Initializes a new instance of the Collection<T> class as a wrapper for the specified list.
意思是: 创建了IList实例的一个包装类实例

var c1 = new Collection<string>();
c1.Add("A"); var c2 = new Collection<string>(c1); // Collection也实现了IList接口
c2.Remove(c2.First()); Console.WriteLine(c2.Count); // 输出 0