我想让我的属性完全私有(获取和设置),如果是这样,更好地使用私有变量而不是属性或使用私有属性本身?
编辑(有关更多问题)
'ok i can use _foo within class and Foo in outside classes
Private _foo As String
Private Property Foo() As String
Get
Return _foo
End Get
Set(value As String)
_foo = value
End Set
End Property
'issue as cannot use _name with class
Property Name as String
'it's ok i can use _age within class but looks not good as e.g above Name... without undescore..
Private _age as Integer
答案 0 :(得分:2)
之间没有真正的区别:
Private _foo As String
Private Property Foo() As String
Get
Return _foo
End Get
Set(value As String)
_foo = value
End Set
End Property
和
Private Foo As String
关键字Private
使其保持在类的范围内。就这样。您现在无法在任何上下文中的任何位置访问Foo
。
然而,使用Property
有几个好处。例如,您可以创建一个属性ReadOnly
进行访问:
Private _foo As String
Public ReadOnly Property Foo() As String
Get
Return _foo
End Get
End Property
这允许在其源自的类之外进行访问。您可以在原始课程中对_foo
进行所有设置,而无需担心课堂外的更改。
Property
的另一个好处是可以引发事件和/或记录更改:
Private _foo As String
Public Property Foo() As String
Get
Return _foo
End Get
Set(value As String)
If Not (value = _foo) Then
_foo = value
NotifyPropertyChanged()
End If
End Set
End Property
您还可以验证正在设置的值和/或更新其他私有字段:
Private _foo As Integer
Public WriteOnly Property Foo() As Integer
Set(value As Integer)
_foo = value
If _foo > 10 Then
_bar = True
End If
End Set
End Property
Private _bar As Boolean
Public ReadOnly Property Bar() As Boolean
Get
Return _bar
End Get
End Property
Property
也可用于DataBinding
,而字段则不能。{/ p>
我确定还有其他差异,但是这应该可以很好地说明您是否需要使用Property
或者字段是否足够好。