什么是从同一类的访问属性的最佳方法,通过访问或直接?是从、属性、直接、方法

由网友(我服许仙敢日蛇)分享简介:这是一些我没有太多一致的约,总是好奇别人做的。This is something I'm not much consistent about and always curious about what other people do.如何访问内部属性(私人或公共)? How do you access inter...

这是一些我没有太多一致的约,总是好奇别人做的。

This is something I'm not much consistent about and always curious about what other people do.

如何访问内部属性(私人或公共)?

How do you access internal properties (private or public)?

例如你有这个属性:

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

在中的另一个功能,哪一个你preFER同一类?为什么?

In the same class within another function which one do you prefer? and why?

_Name = "Johnny"

Name = "Johnny"

忽略,我使用的名称,而不是Me.Name的事实。

推荐答案

我个人preFER使用属性在可能的情况。这意味着你仍然可以得到验证,并可以很容易地把断点的属性访问。这的不的工作,你正在努力做出改变,以这两种性能验证对对方 - 例如,一个最小和最大对,其中每个人都有一个验证约束,使得分钟< = MAX 在任何时候。你可能有(C#):

Personally I prefer to use the property where possible. This means you still get the validation, and you can easily put breakpoints on the property access. This doesn't work where you're trying to make a change to two properties which validate against each other - for instance, a "min and max" pair, where each has a validation constraint such that min <= max at all times. You might have (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;
}

在未来的某个时刻,我希望看到C#获得的财产范围内声明的支持字段的能力,使得它的私有的只是的属性:

public string Name
{
    string name;

    get { return name; }
    set
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }    
        name = value;
    }
}

之外的财产,你将无法获得在名称可言,只有名称。我们已经有了这个自动实现的属性,但它们不能包含任何逻辑。

Outside the property, you wouldn't be able to get at name at all, only Name. We already have this for automatically implemented properties, but they can't contain any logic.

阅读全文

相关推荐

最新文章