Read-only list or unmodifiable list in .NET 4.0

筅森魡賤 提交于 2019-11-28 06:39:41
LukeH

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.

Jason Watts

How about the ReadOnlyCollection already within the framework?

Martin

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.

Paul Betts

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.

Paul Alexander

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!