C# .NET 4.0 中的只读列表或不可修改列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/984042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read-only list or unmodifiable list in .NET 4.0
提问by Chris S
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?
据我所知,.NET 4.0 仍然缺少只读列表。为什么框架仍然缺少这个功能?这不是领域驱动设计最常见的功能之一吗?
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>.
Java 相对于 C# 的少数优势之一是Collections.unmodifiablelist(list)方法的形式,在 IList<T> 或 List<T> 中似乎早就应该这样做了。
Using IEnumerable<T>
is the easiest solution to the question - ToList
can be used and returns a copy.
使用IEnumerable<T>
是问题的最简单解决方案 -ToList
可以使用并返回副本。
采纳答案by LukeH
You're looking for ReadOnlyCollection
, which has been around since .NET2.
您正在寻找ReadOnlyCollection
自 .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.
这将创建一个只读视图,它反映对包装集合所做的更改。
回答by 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.
在 2.0 中,您可以调用AsReadOnly
以获取列表的只读版本。或者将一个存在IList
的ReadOnlyCollection<T>
对象包装在一个对象中。
回答by Jason Watts
How about the ReadOnlyCollectionalready within the framework?
框架中已有的ReadOnlyCollection怎么样?
回答by Ana 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.
如果列表的最常见模式是遍历所有元素,IEnumerable<T>
或者IQueryable<T>
也可以有效地充当只读列表。
回答by Matthew Dresser
回答by Martin
For those who like to use interfaces:
.NET 4.5 adds the generic IReadOnlyList
interface which is implemented by List<T>
for example.
对于那些喜欢使用接口的人:.NET 4.5 增加了IReadOnlyList
由List<T>
example实现的通用接口。
It is similar to IReadOnlyCollection
and adds an Item
indexer property.
它类似于IReadOnlyCollection
并添加了Item
索引器属性。