Differences between Private Fields and Private Properties

后端 未结 6 1791
执笔经年
执笔经年 2020-12-15 15:33

What is the difference between using Private Properties instead of Private Fields

private String MyValue { get; set; }

// instead of

private String _myValu         


        
6条回答
  •  情歌与酒
    2020-12-15 16:14

    Other then what has already been answered, Performance, symantics and completness there is one valid case I have seen for private properties instead of a private field:

    public class Item
    {
        private Item _parent;
        private List _children;
    
        public void Add(Item child)
        {
            if (child._parent != null)
            {
                throw new Exception("Child already has a parent");
            }
            _children.Add(child);
            child._parent=this;
        }
    }
    

    Let's say that we don't want to expose Parent for whatever reason, but we might also want to do validation checks. Should a parent be able to be added as a child to one of its children?

    To resolve this you can make this a property and perform a check for circular references.

提交回复
热议问题