Forbid public Add and Delete for a List

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

    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.

提交回复
热议问题