gpt4 book ai didi

properties - 本地使用私有(private)土地 x 属性(property)的最佳实践

转载 作者:行者123 更新时间:2023-12-02 12:24:47 24 4
gpt4 key购买 nike

当在类内部有一个私有(private)字段并在公共(public)属性上公开该字段时,我应该在类内部使用哪一个?

下面是我想要找出的示例。应该操纵私有(private)字段_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

下课

预先感谢您的帮助。教育

最佳答案

在我看来,您应该尽可能使用属性访问器。这是因为您不必担心拥有属性时可能可用的任何内部逻辑

发生这种情况的一个很好的例子是 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();
}
}
}

注意到“setter”中的所有逻辑了吗?

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

关于properties - 本地使用私有(private)土地 x 属性(property)的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/833047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com