Skip to main content
 首页 » 编程设计

c#之为什么 ObservableCollectionT> 有两个集合构造函数

2024年02月05日28虾米哥

ObservableCollection(T)类有两个构造函数,可以在其中传递项目集合。一个构造函数接受 IEnumerable(T),另一个构造函数接受 List(T)。

鉴于 List(T) 实现了 IEnumerable(T),为什么存在第二个构造函数?

请您参考如下方法:

采用 List 的构造函数是在 .NET 3.0 中引入的,而采用 IEnumerable 的构造函数直到 .NET 3.5 才引入,因此删除 List 构造函数本来是一个刹车变化。

我猜他们写它是为了获取一个 List,发布它,后来意识到它可以更通用。

source code还有一个有趣的评论(不确定是否相关):

    public ObservableCollection(List<T> list) 
        : base((list != null) ? new List<T>(list.Count) : list) 
    { 
        // Workaround for VSWhidbey bug 562681 (tracked by Windows bug 1369339). 
        // We should be able to simply call the base(list) ctor.  But Collection<T> 
        // doesn't copy the list (contrary to the documentation) - it uses the 
        // list directly as its storage.  So we do the copying here. 
        //  
        CopyFrom(list); 
    } 
 
    public ObservableCollection(IEnumerable<T> collection) 
    { 
        if (collection == null) 
            throw new ArgumentNullException("collection"); 
 
        CopyFrom(collection); 
    }