只读在.NET 4.0中列表或修改列表 [英] Read-only list or unmodifiable list in .NET 4.0
问题描述
据我所知,.NET 4.0仍然缺乏只读列表。为什么该框架还缺少这个功能?这不是一个常见的功能性函数为领域驱动设计的?
From what I can tell, .NET 4.0 still lacks read-only lists. Why does the framework still lack this functionality? Isn't this one of the commonest pieces of functionality for domain-driven design?
为数不多的优势Java有过C#这是在的Collections.unmodifiablelist(list)方法,这似乎是在IList的<姗姗来迟; T>或者List< T>
One of the few advantages Java has over C# is this in the form of the Collections.unmodifiablelist(list) method, which it seems is long overdue in IList<T> or List<T>.
使用的IEnumerable< T>
是问题的最简单的解决方案 - 了ToList
CAN使用,并返回一个副本。
Using IEnumerable<T>
is the easiest solution to the question - ToList
can be used and returns a copy.
推荐答案
您正在寻找的 ReadOnlyCollection还
,它已经出现自.NET2。
You're looking for ReadOnlyCollection
, which has been around since .NET2.
IList<string> foo = ...;
// ...
ReadOnlyCollection<string> bar = new ReadOnlyCollection<string>(foo);
或
List<string> foo = ...;
// ...
ReadOnlyCollection<string> bar = foo.AsReadOnly();
这将创建一个只读的视图的,这反映了对所做的更改包裹集合。
This creates a read-only view, which reflects changes made to the wrapped collection.
这篇关于只读在.NET 4.0中列表或修改列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!