如果我通过 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/