dr.*_*vil 4 .net oop properties class accessor
这是我不太一致的事情,并且总是对别人的行为感到好奇.
您如何访问内部属性(私有或公共)?
例如,你有这个属性:
Private _Name As String
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Run Code Online (Sandbox Code Playgroud)
在另一个函数中的同一个类中,您更喜欢哪一个?为什么?
_Name = "Johnny"
Run Code Online (Sandbox Code Playgroud)
要么
Name = "Johnny"
Run Code Online (Sandbox Code Playgroud)
忽略我使用Name而不是Me.Name的事实.
Jon*_*eet 12
我个人更喜欢尽可能使用该物业.这意味着您仍然可以获得验证,并且您可以轻松地在属性访问上添加断点.当您尝试对两个相互验证的属性进行更改时,这不起作用 - 例如,"最小和最大"对,其中每个属性都具有min <= max
始终的验证约束.你可能有(C#):
public void SetMinMax(int min, int max)
{
if (max > min)
{
throw new ArgumentOutOfRangeException("max";
}
// We're okay now - no need to validate, so go straight to fields
this.min = min;
this.max = max;
}
Run Code Online (Sandbox Code Playgroud)
在未来的某个时刻,我想看看C#获得的财产中声明的支持字段,使得它是私有的能力只是属性:
public string Name
{
string name;
get { return name; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
name = value;
}
}
Run Code Online (Sandbox Code Playgroud)
外面的财产,你将无法得到的name
所有,只Name
.我们已经将此用于自动实现的属性,但它们不能包含任何逻辑.
归档时间: |
|
查看次数: |
1469 次 |
最近记录: |