Forbid public Add and Delete for a List

前端 未结 8 1786
被撕碎了的回忆
被撕碎了的回忆 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

    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 _children;
    
      public ReadOnlyCollection 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.

提交回复
热议问题