只读列表或修改的列表,在.NET 4.0中列表、NET

2023-09-04 00:04:20 作者:人心隔两扎

这是我可以告诉,.NET 4.0仍然缺乏只读列表。任何人都可以阐明为什么该框架仍然缺乏这个功能?这不是一个常见的​​功能性函数的领域驱动设计?

From what I can tell, .NET 4.0 still lacks readonly lists. Can anyone shed light on why the framework still lacks this functionality? Isn't this one of the commonest pieces of functionality for domain driven design?

为数不多的优势,Java有对C#是这里的Collections.unmodifiablelist(list)方法,这似乎是早就在IList中或列表。

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 or List.

更新

使用的IEnumerable< T> 是最简单的解决问题的办法 - 了ToList 可用于并返回一个副本

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.