Correct use of C# properties

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

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

OR

publi         


        
12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 16:16

    I personally prefer the first method as it allows you to perform a few operations prior to the return.

    E.G. (A really poor example)

        private int _limit;
        private int _onHand;
        private bool returnToVendor;
    
        public Item(int limit, int onHand)
        {
           _limit = limit;
           _onHand = onHand;
        }
    
        public int ReturnStock
        {
           get
           {
             if(_onHand > _limit)
             {
                returnToVendor = true;
                return _onHand;
             }
           }
    
           set
           {
               _onHand = value;
    
               if(_onHand < _limit)
               {
                  returnToVendor = false;
               }
           }
        }
    

提交回复
热议问题