C# 如何将一个List转换为只读的

如题,主要使用AsReadOnly这个方法就可以了

List<int> a = new List<int> {1, 2, 3, 4, 5}; 
 
IList<int> b = a.AsReadOnly(); // block modification... 
 
IList<int> c = b.AsWritable(); // ... but unblock it again 
 
c.Add(6); 
Debug.Assert(a.Count == 6); // we've modified the original 
 
IEnumerable<int> d = a.Select(x => x); // okay, try this... 
 
IList<int> e = d.AsWritable(); // no, can still get round it 
 
e.Add(7); 

posted @ 2010-05-27 17:59  类型安全的心  阅读(1831)  评论(0编辑  收藏  举报