如果你通过属性相同的类中访问的变量? [英] Should you access a variable within the same class via a Property?

查看:119
本文介绍了如果你通过属性相同的类中访问的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个属性,获取和设置实例变量那么平时你总是使用属性从类外部访问它。

If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it.

我的问题是,你应该也总是在类内这样做?我一直使用的属性(如果有),甚至在类中,但想听到一些争论和反对为这是最正确的,以及为什么。

My question is should you also always do so within the class? I've always used the Property if there is one, even within the class, but would like to hear some arguments for and against as to which is the most correct and why.

或者是它只是一个编码标准在项目中使用?之事

Or is it just a matter of coding standards being used on the project?

推荐答案

一为通过属性访问本地(类范围)变量较强的说法是,你在你的类添加一个抽象层。如果您更改有关该字段存储方式那么你的code的其余部分将不受影响任何逻辑。

One of the stronger argument for accessing local (class scope) variables through properties is that you add a level of abstraction in your class. If you change any logic concerning how that field is stored then the rest of your code will be left unaffected.

例如,你可能会改变,从一个局部变量来一个子对​​象的属性,在数据库调用,一个Web服务调用,以静态属性的一类等等。当进行更改它给你的变化,物业单点,而不必更新您的班上其他同学,因为它们都使用该属性。

For example you might change that from a local variable to a property of a child object, to a database call, to a webservice call, to a static property on a class and so on. When making the change it gives you a single point of change, the property, and you do not have to update the rest of your class since they all use the property.

此外,使用属性使您的财产,而不必在您会直接访问场每个位置执行同样的规则的值应用业务规则。此外,封装

Also using the property enables you to apply business rules on the value of the property instead of having to enforce the same rule at each location where you'd directly access the field. Again, encapsulation

通过引进全自动性能有更少的理由明确有一个局部变量,除非你需要在get / set方法应用业务规则

With the introduction of automatic properties there's even less reason to explicitly have a local variable, unless you need to apply business rules on the get/set

这篇关于如果你通过属性相同的类中访问的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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