老实说,公共变量和公共属性访问器有什么区别?
之间有什么区别:
public string varA;
和
public string varA { get; set; }
Possible Duplicates:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?
What is the difference between:
public string varA;
and
public string varA { get; set; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
公共属性访问器为您将来提供了更大的灵活性。
如果您想在设置值时添加验证,只需编写一个非默认设置器即可。您的其他代码都不需要修改。
也可能有一些原因让您想要用代码替换默认的 getter。对于公共变量来说,这可能是一个真正的痛苦。
The public property accessor gives you more flexibility in the future.
If you want to add validation to setting the value, you simply write a non-default setter. None of your other code would have to be modified.
There could also be reasons you'd want to replace the default getter with code. That can be a real pain with a public variable.
除了其他答案之外,您还可以使用属性来使值只读甚至仅设置:
我也遇到过这样的情况:我后来决定要代理一个对象,或者添加 AOP,这基本上需要特性。
In addition to the other answers, you can also use a property to make the value read-only or even set-only:
I have also run into situations where I later decide I want to proxy an object, or add AOP, which basically requires properties.
公共属性通过公开的 getter 和 setter 方法访问字段和内部类代码。公共字段直接访问该字段。
使用属性可以提供抽象和设计层(使集合访问器受保护、私有的能力)。
当指定属性并且不存在主体时,编译器将创建一个底层私有字段,用于存储该值。本质上:
一般来说,我倾向于使用公共暴露变量的属性和私有字段。如果某个字段被多次访问并且速度是至关重要的设计要求,我可能会考虑使用该字段。
Public property accesses fields and internal class code through exposed getter and setter methods. A public field acesses the field directly.
Using propertys offers the potential to provide a layer of abstraction and design (ability to make set accessor protected, private).
When a property is specified and no body present an underlying private field is created by the compiler that is used to store the value against. Essentially:
In general I tend to use properties for public exposed variables and fields for private. I might consider using a field if that field was accessed many times and speed was a crucial design requirement.