在包含类,使用属性或字段? [英] Within the Containing Class, Use Property or Field?

查看:122
本文介绍了在包含类,使用属性或字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是使用私有字段,或者属性很好的做法,在包含它们的类编写代码时?

Is it good practice to use the private field, or the property, when writing code in the class that contains them?

例如,如果我有这个字段/属性对,类之外这个类必须使用属性。什么代码 类里面呢? ?它应该使用私有字段,或者它也应该去通过属性

For example, if I have this field/property pair, classes outside this class must use the property. What about code inside the class? Should it use the private field, or should it also go through the property?

private string _foo;

protected string Foo
{
    get { return this._foo; }
}

private void SomeMethod()
{
  string dummyVariable = "snuh" + this._foo;  // So, this...
  string dummyVariable = "snuh" + this.Foo;  // ... or this?
}



这里使用属性的一个优点,是如果在任何逻辑吸气,它仍然会得到执行。我很想知道,如果有一个最佳实践的政策在这里跟随。

One advantage of using the property here, is if there is any logic in the getter, it will still get executed. I'm curious to know if there is a best-practice policy to follow here.

推荐答案

在使用的Auto-Implemented性能的,你没有选择 - 你的必须的使用属性,因为你不必产生磁场的任何访问。

When using Auto-Implemented properties, you don't have a choice - you must use the property, as you don't have any access to the generated field.

如果您属性不是简单的做一些额外的工作(验证,触发事件等...) ,你应该致电酒店,以集中访问和逻辑。

If you property is not simple and does some extra work (validation, firing events etc...), you should call the property in order to centralize access and logic.

如果您有任何其他属性(即无逻辑和一个支持字段一个简​​单的属性)我想问他们为什么上面...

If you have any other properties (meaning a simple property with no logic and a backing field) I would ask why are they not one of the above...

随着你给的例子中,差别不大 - 与你同在如何使用一致更重要的是这真的归结为个人的美学和编码风格。

With the example you have give, it makes little difference - it is more important to be consistent with how you use these and really boils down to personal aesthetics and coding style.

这篇关于在包含类,使用属性或字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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