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

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

问题描述

这是我不太一致的事情,并且总是对其他人的行为感到好奇.

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

在另一个函数的同一个类中,你更喜欢哪个?为什么?

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

_Name = "Johnny"

Name = "Johnny"

忽略我使用 Name 而不是 Me.Name 的事实.

推荐答案

我个人更喜欢尽可能使用该属性.这意味着您仍然可以获得验证,并且您可以轻松地在属性访问上放置断点.这在您尝试更改相互验证的两个属性时 不起作用 - 例如,最小和最大"对,其中每个都有一个验证约束,使得 min <= 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# 能够在属性中声明支持字段,这样它只是属性是私有的:

At some point in the future, I'd like to see C# gain the ability to declare the backing field within the property, such that it's private to just the property:

public string Name
{
    string name;

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

在属性之外,您根本无法获得name,只能获得Name.我们已经为自动实现的属性提供了这个,但它们不能包含任何逻辑.

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天全站免登陆