Read-only list or unmodifiable list in .NET 4.0

2019-01-17 08:50发布

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?

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

Using IEnumerable<T> is the easiest solution to the question - ToList can be used and returns a copy.

6条回答
乱世女痞
2楼-- · 2019-01-17 09:35

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.

查看更多
女痞
3楼-- · 2019-01-17 09:36

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.

查看更多
劫难
4楼-- · 2019-01-17 09:38
地球回转人心会变
5楼-- · 2019-01-17 09:43

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.

查看更多
叼着烟拽天下
6楼-- · 2019-01-17 09:44

How about the ReadOnlyCollection already within the framework?

查看更多
我只想做你的唯一
7楼-- · 2019-01-17 09:54

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.

查看更多
登录 后发表回答