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.

推荐答案

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.

.net相关问答推荐

Azure Function应用程序-如何升级.NET运行时

跨请求共享数据

竖线在 PropertyGroup .csproj 文件中的含义

通过 System.Net.Mail 的 VB SMTP 停止工作

如何使用 C# 关键字作为属性名称?

如何判断 IOException 是否为 Not-Enough-Disk-Space-Exception 类型?

如何以编程方式判断类型是 struct 还是类?

如何将自定义 UserControl 显示为对话框?

为什么字典比列表快得多?

是否有用于 Windows / C# 开发的可嵌入 Webkit 组件?

大型 WCF Web 服务请求因 (400) HTTP 错误请求而失败

我不了解应用程序域

将 StreamReader 返回到开头

如何知道 DateTime 是否在 C# 中的 DateRange 之间

IEnumerable vs IReadonlyCollection vs ReadonlyCollection 用于公开列表成员

合并两个(或更多)PDF

具有不同身份验证标头的 HttpClient 单个实例

将控制台输出镜像到文件

Linq Query 不断抛出无法创建 System.Object 类型的常量值......,为什么?

泛型类的静态成员是否与特定实例相关联?