2017-03-20 13 views
1

プロパティの代わりにプライベート変数を使用するかプライベートプロパティ自体を使用する方が良い場合は、自分のプロパティを完全にプライベート(取得して設定)にしたいと思いますか? (さらにご質問の場合)セッターとゲッターの完全プライベートプロパティ

EDIT

'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 
+1

@Bugsだからどちらか一方を使うことができますが、私はprivateプロパティの代わりにprivate変数を使うと思います。しかし、私が見たいと思っていないことの1つは、私のクラスがプライベート変数と混合されたプロパティを含んでいることです。 –

答えて

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を使用することには2つの利点があります。一つは、あなたがアクセスのプロパティ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にも使用できますが、フィールドでは使用できません。

これ以外にも違いがありますが、Propertyを使用する必要があるかどうか、またはフィールドが十分であるかどうかを示す良い指標が必要です。

関連する問題