Forbid public Add and Delete for a List

前端 未结 8 1815
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 02:11

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:58

    Beside of implementing your own IList<T> you could return a ReadOnlyCollection<MyClass>.

    public MyClass
    {
        public MyClass Parent;
    
        private List<MyClass> children;
        public ReadOnlyCollection<MyClass> Children
        {
            get { return children.AsReadOnly(); }
        }
    }
    
    0 讨论(0)
  • 2021-02-19 02:58

    You can encapsulate the list in the class by making it private, and offer it as a ReadOnlyCollection:

    public class MyClass {
    
      public MyClass Parent { get; private set; };
    
      private List<MyClass> _children;
    
      public ReadOnlyCollection<MyClass> Children {
        get { return _children.AsReadOnly(); }
      }
    
      public void AddChild(MyClass item) {
        item.Parent = this;
        _children.Add(item);
      }
    
      public void DeleteChild(MyClass item) {
        item.Parent = null;
        _children.Remove(item);
      }
    
    }
    

    You can make the Parent a property with a private setter, that way it can't be modified from the outside, but the AddChild and DeleteChild methods can change it.

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