繁体   English   中英

C#中的只读列表

[英]Read-Only List in C#

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

class Foo {
  private List<int> myList;
}

我想提供对该字段的访问权限,仅供阅读。

即我想要属性可以访问 Enumerable、Count 等,但不能访问 Clear、Add、Remove 等。我该怎么做?

您可以使用AsReadOnly()方法将List<T>公开为ReadOnlyCollection<T>

C# 6.0 及更高版本(使用Expression Bodied Properties

class Foo { 

  private List<int> myList;

  public ReadOnlyCollection<int> ReadOnlyList => myList.AsReadOnly();

}

C# 5.0 及更早版本

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM