Correct use of C# properties

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

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

OR

publi         


        
12条回答
  •  死守一世寂寞
    2020-12-16 15:56

    Use the former if you need to add some kind of logic to your getter/setters.

    Use the latter otherwise. It makes things much cleaner. You can also achieve read-only properties using auto properties:

    public List Dates { get; private set; }
    

    Or, if you don't want people to add any items to the list through the property you can resort to the former syntax:

    private List _dates = new List();
    private ReadOnlyCollection _readOnlyDates =
        new ReadOnlyCollection(_dates);
    
    public ReadOnlyCollection Dates
    {
        get { return _readOnlyDates; }
    }
    

提交回复
热议问题