Forbid public Add and Delete for a List

前端 未结 8 1219
我在风中等你
我在风中等你 2021-02-19 02:12

in my C#-project, I have a class which contains a List

public class MyClass
{
  public MyClass parent;
  public List children;
  ...
}


        
相关标签:
8条回答
  • 2021-02-19 02:55

    Use List(T).AsReadOnly().

    http://msdn.microsoft.com/en-us/library/e78dcd75.aspx

    Returns a read-only IList<(Of <(T>)>) wrapper for the current collection.

    Available since .NET 2.0.

    0 讨论(0)
  • 2021-02-19 02:56

    If you hand the caller the List<T>, you can't control this; you can't even subclass List<T>, since the add/remove are not virtual.

    Instead, then, I would expose the data as IEnumerable<MyClass>:

    private readonly List<MyClass> children = new List<MyClass>();
    public void AddChild(MyClass child) {...}
    public void RemoveChild(MyClass child) {...}
    public IEnumerable<MyClass> Children {
        get {
            foreach(var child in children) yield return child;
        }
    }
    

    (the yield return prevents them just casting it)

    The caller can still use foreach on .Children, and thanks to LINQ they can do all the other fun things too (Where, First, etc).

    0 讨论(0)
提交回复
热议问题