Forbid public Add and Delete for a List

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

    Make the list private, and create public methods to access its content from outside the class.

    public class MyClass
    {
        public MyClass Parent { get; private set; }
    
        private List _children = new List();
        public IEnumerable Children
        {
            get
            {
                // Using an iterator so that client code can't access the underlying list
                foreach(var child in _children)
                {
                    yield return child;
                }
            }
        }
    
        public void AddChild(MyClass child)
        {
            child.Parent = this;
            _children.Add(child);
        }
    
        public void RemoveChild(MyClass child)
        {
            _children.Remove(child);
            child.Parent = null;
        }
    }
    

    By the way, avoid declaring public fields, because you can't control what client code does with them.

提交回复
热议问题