当地使用私人土地x财产的最佳做法

Edu*_*Edu 2 properties private private-members

在一个类中,你有一个私有的fiels并在公共属性上公开该字段,我应该从类中使用哪一个?

下面是我想要了解的一个例子.应该控制私人领域_Counter还是财产柜台?

公共课堂考试

Private _Counter As Integer

Public Property Counter() As Integer
    Get
        Return _Counter
    End Get
    Set(ByVal value As Integer)
        _Counter = value
    End Set
End Property

Private Sub Dosomething()

    'What is the best practice?
    'Direct access to private field or property?

    'On SET
    _Counter += 1
    'OR
    Me.Counter += 1

    'On Get
    Console.WriteLine(_Counter)
    Console.WriteLine(Me.Counter)

End Sub
Run Code Online (Sandbox Code Playgroud)

结束班

在此先感谢您的帮助.埃杜

Pur*_*ome 5

IMO你应该尽可能使用Property访问者.这是因为您不必担心拥有属性时可能存在的任何内部逻辑.

发生这种情况的一个很好的例子是Linq DataContext中的代码.

看一下这个...

[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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意'setter'中的所有逻辑?

这就是为什么开始调用你的属性而不是字段IMO的做法很重要.