[英]Read-Only List in C#
我有一些帶有List
-property 的類:
class Foo {
private List<int> myList;
}
我想提供對該字段的訪問權限,僅供閱讀。
即我想要屬性可以訪問 Enumerable、Count 等,但不能訪問 Clear、Add、Remove 等。我該怎么做?
您可以使用AsReadOnly()
方法將List<T>
公開為ReadOnlyCollection<T>
class Foo {
private List<int> myList;
public ReadOnlyCollection<int> ReadOnlyList => myList.AsReadOnly();
}
class Foo {
private List<int> myList;
public ReadOnlyCollection<int> ReadOnlyList {
get {
return myList.AsReadOnly();
}
}
}
如果您想要列表的只讀視圖,您可以使用ReadOnlyCollection<T>
。
class Foo {
private ReadOnlyCollection<int> myList;
}
我會去
public sealed class Foo
{
private readonly List<object> _items = new List<object>();
public IEnumerable<object> Items
{
get
{
foreach (var item in this._items)
{
yield return item;
}
}
}
}
現在有一個不可變集合庫可以做到這一點。 您可以通過 nuget 安裝。
從 .NET Framework 4.5 開始支持不可變集合類。
https://msdn.microsoft.com/en-us/library/dn385366%28v=vs.110%29.aspx
System.Collections.Immutable 命名空間提供可用於這些場景的通用不可變集合類型,包括:ImmutableArray<T>、ImmutableDictionary<Tkey,TValue>、ImmutableSortedDictionary<T>、ImmutableHashSet<T>、ImmutableList<T>、ImmutableQueue <T>、ImmutableSortedSet<T>、ImmutableStack<T>
用法示例:
class Foo
{
public ImmutableList<int> myList { get; private set; }
public Foo(IEnumerable<int> list)
{
myList = list.ToImmutableList();
}
}
如果您在類中聲明只讀列表,您仍然可以向其中添加項目。
如果您不想添加或更改任何內容,則應按照 Darin 的建議使用ReadOnlyCollection<T>
。
如果您想從列表中添加、刪除項目但不想更改內容,您可以使用readonly List<T>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.