プロパティでプライベートセットを使用し、ReadOnlyプロパティにする場合はどのような状況ですか?以下の非常に単純な2つの例を考慮してください。
最初の例:
Public Class Person
Private _name As String
Public Property Name As String
Get
Return _name
End Get
Private Set(ByVal value As String)
_name = value
End Set
End Property
Public Sub WorkOnName()
Dim txtInfo As TextInfo = _
Threading.Thread.CurrentThread.CurrentCulture.TextInfo
Me.Name = txtInfo.ToTitleCase(Me.Name)
End Sub
End Class
// ----------
public class Person
{
private string _name;
public string Name
{
get { return _name; }
private set { _name = value; }
}
public void WorkOnName()
{
TextInfo txtInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
this.Name = txtInfo.ToTitleCase(this.Name);
}
}
2番目の例:
Public Class AnotherPerson
Private _name As String
Public ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Sub WorkOnName()
Dim txtInfo As TextInfo = _
Threading.Thread.CurrentThread.CurrentCulture.TextInfo
_name = txtInfo.ToTitleCase(_name)
End Sub
End Class
// ---------------
public class AnotherPerson
{
private string _name;
public string Name
{
get { return _name; }
}
public void WorkOnName()
{
TextInfo txtInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
_name = txtInfo.ToTitleCase(_name);
}
}
どちらも同じ結果をもたらします。これは善悪の状況ではなく、単に好みの問題ですか?
public string Name { get; protected set; }
継承を通じて。