List如何显示带有只读列表的复制构造函数?

发布于 2024-10-06 06:20:14 字数 264 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

妖妓 2024-10-13 06:20:14

不,第二个列表不是只读的,它仍然是从 < 生成的列表code>IEnumerable(特别是 ICollection此处)。 .AsReadOnly() 方法只是给出ReadOnlyCollection,但我们当弄乱第二个列表时,不会修改那个集合。

相反,您创建了一个新的 List 及其可编辑的成员(通过 List(IEnumerable)构造函数)。这与任何其他 ICollectionIEnumerable 源一样进行生成,它执行 .CopyTo() 下面。

对于 ReadOnlyCollection(实现 ICollection),它调用 .CopyTo() 位于其来源下方的原始 IList 上,所以基本上你所拥有的与:

List<MyObject> FirstList = new List<MyObject>();
// Add items to FirstList.
List<MyObject> SecondList = new List<MyObject>(FirstList);

....就第二个列表而言。在其他情况下,传递给构造函数的 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 an ICollection<T> here). The .AsReadOnly() method just gives a ReadOnlyCollection<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 the List<T>(IEnumerable<T>) constructor). This does the generation like any other IEnumerable<T> source that's an ICollection<T>, it performs a .CopyTo() underneath.

In the case of a ReadOnlyCollection<T> (which implements ICollection<T>), it's calling .CopyTo() on the original IList<T> underneath that it was from, so basically what you have is the same as:

List<MyObject> FirstList = new List<MyObject>();
// Add items to FirstList.
List<MyObject> SecondList = new List<MyObject>(FirstList);

....as far as the second list is concerned. In other cases where the IEnumerable<T> passed to the constructor is not a ICollection<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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文