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?
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?
不,第二个列表不是只读的,它仍然是从IEnumerable<T>
(特别是ICollection<T>
此处)生成的列表。该.AsReadOnly()
方法只给出了一个ReadOnlyCollection<MyObject>
,但我们在处理第二个列表时不会修改该集合。
相反,您创建了一个新List<MyObject>
的,其成员是可编辑的(通过List<T>(IEnumerable<T>)
构造函数)。这会像任何其他IEnumerable<T>
来源一样生成ICollection<T>
,它在.CopyTo()
下面执行。
在 a ReadOnlyCollection<T>
(实现ICollection<T>
)的情况下,它调用它所来自.CopyTo()
的原始IList<T>
底层,所以基本上你所拥有的与以下内容相同:
List<MyObject> FirstList = new List<MyObject>();
// Add items to FirstList.
List<MyObject> SecondList = new List<MyObject>(FirstList);
....就第二个列表而言。在IEnumerable<T>
传递给构造函数的其他情况下不是a ICollection<T>
,它将迭代集合和.Add()
每个成员......但它仍然不会影响新列表及其成员的可变性。