开发者

Read-Only List in C#

开发者 https://www.devze.com 2023-02-03 20:35 出处:网络
I have some class with List-property: class Foo { private List<int> myList; } I want provide access to this field only for read.

I have some class with List-property:

class Foo {
  private List<int> myList;
}

I want provide access to this field only for read.

I.e. I want property with access to Enumerable, Count,开发者_开发问答 etc. and without access to Clear, Add, Remove, etc. How I can do it?


You can expose a List<T> as a ReadOnlyCollection<T> by using the AsReadOnly() method

C# 6.0 and later (using Expression Bodied Properties)

class Foo { 

  private List<int> myList;

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

}

C# 5.0 and earlier

class Foo {

  private List<int> myList;

  public ReadOnlyCollection<int> ReadOnlyList {
     get {
         return myList.AsReadOnly();
     }
  }
}


If you want a read-only view of a list you could use ReadOnlyCollection<T>.

class Foo {
    private ReadOnlyCollection<int> myList;
}


i would go for

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;
            }
        }
    }
}


There is now an Immutable Collections library that does exactly that. Which you can install via nuget.

The immutable collection classes are supported starting with the .NET Framework 4.5.

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

The System.Collections.Immutable namespace provides generic immutable collection types that you can use for these scenarios, including: ImmutableArray<T>, ImmutableDictionary<Tkey,TValue>, ImmutableSortedDictionary<T>, ImmutableHashSet<T>, ImmutableList<T>, ImmutableQueue<T>, ImmutableSortedSet<T>, ImmutableStack<T>

Example of Usage:

class Foo
{
    public ImmutableList<int> myList { get; private set; }

    public Foo(IEnumerable<int> list)
    {
        myList = list.ToImmutableList();
    }
}


If you declare a readonly list in your class, you'll still be able to add items to it.

If you don't want to add or change anything, you should be using ReadOnlyCollection<T> as Darin suggested.

If you want to add, remove items from the list but don't want to change the content, you can use a readonly List<T>.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号