是否应该通过属性访问同一个类中的变量? [英] Should you access a variable within the same class via a Property?

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

问题描述

如果您有一个获取和设置实例变量的属性,那么通常您总是使用该类外部的属性来访问它.

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?

推荐答案

通过属性访问本地(类范围)变量的一个更有力的论据是您在类中添加了一个抽象级别.如果您更改关于该字段如何存储的任何逻辑,那么您的其余代码将不受影响.

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.

例如,您可以将其从局部变量更改为子对象的属性、数据库调用、网络服务调用、类的静态属性等等.进行更改时,它会为您提供一个单一的更改点,即属性,并且您不必更新类的其余部分,因为它们都使用该属性.

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