NET 4.0中的只读列表或不可修改列表

据我所知。NET 4.0仍然缺少只读列表。为什么框架仍然缺乏这个功能?这难道不是 领域驱动设计最常见的功能之一吗?

Java 相对于 C # 的少数优势之一是 不可修改列表(list)方法的形式,在 IList < T > 或 List < T > 中似乎早就应该这样做了。

使用 IEnumerable<T>是这个问题最简单的解决方案-ToList可以被使用并返回一个副本。

51106 次浏览

In 2.0 you can call AsReadOnly to get a read-only version of the list. Or wrap an existing IList in a ReadOnlyCollection<T> object.

How about the ReadOnlyCollection already within the framework?

You're looking for ReadOnlyCollection, which has been around since .NET2.

IList<string> foo = ...;
// ...
ReadOnlyCollection<string> bar = new ReadOnlyCollection<string>(foo);

or

List<string> foo = ...;
// ...
ReadOnlyCollection<string> bar = foo.AsReadOnly();

This creates a read-only view, which reflects changes made to the wrapped collection.

If the most common pattern of the list is to iterate through all the elements, IEnumerable<T> or IQueryable<T> can effectively act as a read-only list as well.

For those who like to use interfaces: .NET 4.5 adds the generic IReadOnlyList interface which is implemented by List<T> for example.

It is similar to IReadOnlyCollection and adds an Item indexer property.

Create an extension method ToReadOnlyList() on IEnumerable, then

IEnumerable<int> ints = new int[] { 1, 2, 3 };
var intsReadOnly = ints.ToReadOnlyList();
//intsReadOnly [2]= 9; //compile error, readonly

here is the extension method

public static class Utility
{
public static IReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> items)
{
IReadOnlyList<T> rol = items.ToList();
return rol;
}
}

see Martin's answer too