什么是从同一类的访问属性的最佳方法,通过访问或直接? [英] What is the best way to access properties from the same class, via accessors or directly?

查看:177
本文介绍了什么是从同一类的访问属性的最佳方法,通过访问或直接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于什么是从同一类的访问属性的最佳方法,通过访问或直接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆