C#中的只读列表

我有一些带有List -property的类:

 class Foo { private List myList; } 

我想提供对此字段的访问权限仅供读取。

即我希望属性可以访问Enumerable,Count等,而无需访问Clear,Add,Remove等。我怎么能这样做?

如果您想要列表的只读视图,可以使用ReadOnlyCollection

 class Foo { private ReadOnlyCollection myList; } 

您可以使用方法AsReadOnly()List公开为ReadOnlyCollection

 class Foo { private List myList; public ReadOnlyCollection ReadOnlyList { get { myList.AsReadOnly(); } } } 

巧妙的是,如果您从私人列表中添加/删除任何内容,它也会反映在返回的ReadOnlyCollection中

我会去的

 public sealed class Foo { private readonly List _items = new List(); public IEnumerable Items { get { foreach (var item in this._items) { yield return item; } } } } 

现在有一个Immutable Collections库正是这样做的。 您可以通过nuget安装。

从.NET Framework 4.5开始支持不可变集合类。

https://msdn.microsoft.com/en-us/library/dn385366%28v=vs.110%29.aspx

System.Collections.Immutable命名空间提供了可用于这些方案的通用不可变集合类型,包括:ImmutableArray ,ImmutableDictionary ,ImmutableSortedDictionary ,ImmutableHashSet ,ImmutableList ,ImmutableQueue ,ImmutableSortedSet ,ImmutableStack

用法示例:

 class Foo { public ImmutableList myList { get; private set; } public Foo(IEnumerable list) { myList = list.ToImmutableList(); } } 

如果您在class级中声明了一个只读列表,您仍然可以向其中添加项目。

如果您不想添加或更改任何内容,则应使用Darin建议的ReadOnlyCollection

如果要添加,删除列表中的项目但不想更改内容,可以使用readonly List