List如何显示带有只读列表的复制构造函数?
MSDN 文章并没有真正解释这一点。
List<MyObject> FirstList = new List<MyObject>();
// Add items to FirstList.
List<MyObject> SecondList = new List<MyObject>(FirstList.AsReadOnly());
// Is SecondList a read-only collection?
The MSDN article doesn't really explain this.
List<MyObject> FirstList = new List<MyObject>();
// Add items to FirstList.
List<MyObject> SecondList = new List<MyObject>(FirstList.AsReadOnly());
// Is SecondList a read-only collection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,第二个列表不是只读的,它仍然是从 < 生成的列表code>IEnumerable (特别是
ICollection
此处)。.AsReadOnly()
方法只是给出ReadOnlyCollection
,但我们当弄乱第二个列表时,不会修改那个集合。相反,您创建了一个新的
List
及其可编辑的成员(通过List(IEnumerable)
构造函数)。这与任何其他ICollection
的IEnumerable
源一样进行生成,它执行.CopyTo()
下面。对于
ReadOnlyCollection
(实现ICollection
),它调用.CopyTo()
位于其来源下方的原始IList
上,所以基本上你所拥有的与:....就第二个列表而言。在其他情况下,传递给构造函数的
IEnumerable
不是ICollection
,它会迭代集合并 a href="http://msdn.microsoft.com/en-us/library/3wcytfd1.aspx" rel="nofollow">.Add()
每个成员.. .但它仍然不会对新列表及其成员的可变性产生影响。No, the second list is not read-only, it's still a List generated from an
IEnumerable<T>
(specifically anICollection<T>
here). The.AsReadOnly()
method just gives aReadOnlyCollection<MyObject>
, but we're not modifying that collection when messing with the second list.Instead, you've created a new
List<MyObject>
with its members that is editable (via theList<T>(IEnumerable<T>)
constructor). This does the generation like any otherIEnumerable<T>
source that's anICollection<T>
, it performs a.CopyTo()
underneath.In the case of a
ReadOnlyCollection<T>
(which implementsICollection<T>
), it's calling.CopyTo()
on the originalIList<T>
underneath that it was from, so basically what you have is the same as:....as far as the second list is concerned. In other cases where the
IEnumerable<T>
passed to the constructor is not aICollection<T>
, it would iterate over the collection and.Add()
each member instead...but it would still have no impact on the mutability of the new list and its members.