为什么要使用属性而不是可变的 [英] Why to use Property and not Variable

查看:103
本文介绍了为什么要使用属性而不是可变的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常建议我们不要使用公共变量,而要使用属性.
如果我可以对公共变量执行相同的操作,那么为什么要使用属性?

解决方案

因为它是公共属性,所以您可以更改类的内部不影响外界.

例如,如果您有一个带有公共变量"username"的类,其中包含"Paul Jones先生"和"Alison Mary Smith先生"之类的数据,则它可以正常工作. 直到您意识到如果使用四个名称部分来代替类,效果会更好:

Status title;
string firstName;
string middleNames;
string lastName;

外界会怎样?每个使用您的类的类都依赖于用户名":但是它不存在!

如果username是一个属性,则可以提供一个getter和setter使其与内部表单一起使用,但看起来就像旧类的外部表单一样-外部的任何更改都不需要更改,您只需测试修订后的类即可. /blockquote>

查看这些文章,可以帮助您了解为什么需要财产:

http://dotnetguts.blogspot.com/2007/07/advantage-of-using- properties.html [^ ]

http://www.devarticles.com/c/a/C -Sharp/Understanding-Properties-in-C-Sharp/ [ :-)


We are mostly suggested to not to use public variables, but to told to use property.
if i can do same thing with public variable, then why to use property?

Because if it is a public property, then you can change the internals of your class without affecting the outside world.

For example, if you have a class with a public variable "username" which holds data like "Mr Paul Jones" and "Mrs Alison Mary Smith", it works fine.
Until you realise that your class would work better if you used four name parts instead:

Status title;
string firstName;
string middleNames;
string lastName;

What happens to the outside world? Every class that used yours relies on "username": but it doesn''t exist!

If username is a property, you can provide a getter and a setter that makes it work with the internal form, but looks just like the external form to legacy classes - nothing outside needs to change, you just have to test your revised class.


Check out these articles which can help you to understand why property is needed :

http://dotnetguts.blogspot.com/2007/07/advantage-of-using-properties.html[^]

http://www.devarticles.com/c/a/C-Sharp/Understanding-Properties-in-C-Sharp/[^]


Because properties enforces encapsulation that is a fundamental OOP concept: they allow changing the object''s behaviour without directly ''touching'' the object internals.
:-)


这篇关于为什么要使用属性而不是可变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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