c# - Collection<T> 是封装 IList<T> 还是枚举 IList<T>?

标签 c#

如果我通过 Collection 属性公开内部成员:

public Collection<T> Entries
{
    get { return new Collection<T>(this.fieldImplimentingIList<T>); }
}

当这个属性被调用时会发生什么?例如,调用以下代码行时会发生什么:

T test = instanceOfAbove.Entries[i];
instanceOfAbove[i] = valueOfTypeT;

很明显,每次调用此属性时都会创建一个新的引用类型,但实际发生了什么?它只是包装 IList<T> 吗?在下面,它是否枚举了 IList<T>并创建一个新的 Collection<T>实例?如果在 for 中使用此属性,我会担心性能循环。

最佳答案

根据 Reflector,新的 Collection<T>只是包装 IList<T> :

public Collection(IList<T> list)
{
    if (list == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
    }
    this.items = list;
}

来自the docs :

Initializes a new instance of the Collection<(Of <(T>)>) class as a wrapper for the specified list.

(强调)

因此开销是最小的(不枚举列表),并且对返回集合的更改将影响原始列表。

(顺便说一下,我假设您指的是 System.Collections.ObjectModel.Collection<T>——在顶级 System.Collections 命名空间中没有 Collection 的通用版本。)

关于c# - Collection<T> 是封装 IList<T> 还是枚举 IList<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2436604/

相关文章:

c# - 在 View 中生成新 anchor 时,我可以强制 T4MVC 不要从当前 View 的 URL 中获取参数吗?

c# - 为什么 AsQueryable<T> 不暗示 _t 鉴别器上的过滤器

c# - 如何使用 Java 客户端导入 WCF Web 服务

c# - indexOf 查找空字符串

c# - 将类似的方法移动到通用实现中

c# - 如何使用 SQLite-Net Extensions 实现递归关系

c# - 嵌套的 foreach 循环读取 .xml 并将对象写入列表

c# - 如何在 asp.net(c#) 中使文本框不可编辑

c# - 在 WCF 中使用共享数据类型作为 DataContract

c# - RSS 提要 XMLDataSource 过滤器 RSS 项目