有关访问成员变量的疑问 [英] Doubt regarding in the accessing of a member variable

查看:60
本文介绍了有关访问成员变量的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我对成员变量有疑问.为什么要保留成员

变量作为私有变量,并通过get属性将其提供给输出.

在此先谢谢您.

Hi all,

I have a doubt regarding the member variable.Why we are keeping member

variables as private and providing it to the output through the get property.

Thanks in advance.

推荐答案

,以便您可以更改应用程序的内部结构而不会影响外部环境.如果公开内部变量,则必须在其余时间内使用那些不变的变量,否则可能会以难以解释的方式破坏外部代码.
另外,属性允许您做额外的工作-例如验证或脏位"设置,而这些字段则不行.
So that you can change the internals of your application without affecting the outside world. If you expose your internal variables, then you have to work with those variables unchanged for the rest of time, or risk breaking external code in difficult to explain ways.
In addition, properties allow you to do extra work - such as validation, or "dirty bit" setting, which fields do not.


其用途之一是控制对该成员变量的访问.并在任何人读取其值时发生一个事件(您可以更改其真实值并返回另一件事,或者可以更新对象的某些内部状态)
One of its usages is to control access to that member variable and have an event whenever anyone reads its value (and you may change its real value and return another thing or may you update some internal state of your object)


这不是必需的(考虑到成为坏风格"),直到:

1.您需要将该成员设置为只读
2.您正在实现需要该属性存在的特定接口
3.您只是隐藏了计算结果的精确方法,该方法不是直接存储在字段中,而是从其他属性或成员获得的,并且将值表示为属性,以便与真实"方法更好地区分.
4.仅当您要求时,您才可以进行上述计算. Ofc.有很多理由改为使用方法...
5.当有人修改成员的值时,您想向类提供其他逻辑-例如引发事件或验证数据是否正确,或释放某些依赖资源...或其他任何方法...
6.其他想法?我认为可以找到一些:)

通常,当这仅是某个值的存储时,可以仅使用公共字段(但使用名称具有属性的名称,因此"Id"而不是"_id")是可以的.当需要一些其他逻辑时,将其更改为Property不会对使用它的代码产生任何影响(当然,除非您限制对成员的访问...).

问候
Seb
This is not required (while considered to be a "bad style"), until:

1. You need to make this member read-only
2. You are implementing specific interface that requires presence of such property
3. You just hiding exact method that calculates result that is not stored directly in the field, but obtained from other properties or members, and presents value as property to be better distinguished from "real" methods.
4. You wan''t to make calculation above only when requested. Ofc. there is a lot reasons to use method instead...
5. You want to provide additional logic to the class when someone modifies the value of the member - like throwing an event or validating data for being correct, or releasing some dependant resource... or whatever else...
6. Other ideas? I assume one can find a few :)

Generally this is sorta OK to use only public field (but with name like would property have, so "Id" not "_id") when this is just a storage for some value. Changing it into Property when some additional logic is required, will have no impact on a code that uses it (ofcourse until you limit access to the member...).

Regards
Seb


这篇关于有关访问成员变量的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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