Forbid public Add and Delete for a List

前端 未结 8 1216
我在风中等你
我在风中等你 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:47

    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.

提交回复
热议问题