Best Practice on local use of Private Field x Property

后端 未结 9 1617
萌比男神i
萌比男神i 2021-01-22 02:09

When inside a class you have a private fiels and expose that field on a public property, which one should I use from inside the class?

Below you is an example on what I

9条回答
  •  一向
    一向 (楼主)
    2021-01-22 02:40

    IMO you should be using the Property accessor whenever possible. This is because you don't have to worry about any internal logic that might be available when you have an a property.

    A good example of where this happens is in the code behind in a Linq DataContext.

    check this out...

    [Column(Storage="_ReviewType", DbType="TinyInt NOT NULL")]
    public byte ReviewType
    {
        get
        {
            return this._ReviewType;
        }
        set
        {
            if ((this._ReviewType != value))
            {
                this.OnReviewTypeChanging(value);
                this.SendPropertyChanging();
                this._ReviewType = value;
                this.SendPropertyChanged("ReviewType");
                this.OnReviewTypeChanged();
            }
        }
    }
    

    Notice all that logic in the 'setter'?

    This is why it's important to start getting into the practice of calling your Properties instead of fields, IMO.

提交回复
热议问题