且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么要使用属性而不是可变的

更新时间:2022-11-01 16:52:10

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

例如,如果您有一个带有公共变量"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.
:-)