Correct use of C# properties

后端 未结 12 675
生来不讨喜
生来不讨喜 2020-12-16 15:19
private List _dates;

public List Dates
{
    get { return _dates; }
    set { _dates = value; }
}

OR

publi         


        
12条回答
  •  旧巷少年郎
    2020-12-16 16:17

    The former is the original approach, the latter is an example of the newer 'auto properties' facility whereby the compiler generates a backing field for you automatically.

    Some people (myself included) shy away from auto properties because the syntax is easy to mistake for abstract properties, there is no facility for 'readonly' properties and the syntax for auto properties with private setters is clumsy:

    public List Dates
    {
        get;
        private set;
    }

    I also find it uncomfortable to have my classes' internal implementation accessing fields via the class API.

提交回复
热议问题