C# 中 get、set 属性的真正目的是什么?
可能的重复:
属性与方法
C#:公共字段与自动属性
- get,set 的真正目的是什么 C# 中的属性?
- 任何好的前我应该什么时候使用 get,set 属性...
Possible Duplicates:
Properties vs Methods
C#: Public Fields versus Automatic Properties
- What is the real purpose of get,set
properties in c#? - Any good ex when should i use get,set properties...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要它们来控制您的对象私有字段值。例如,如果您不想允许整数为空或负值。此外,封装对于在对象成员值更改时触发事件很有用。
示例
另一个示例
以及只读属性的另一个实现如下
you need them to have control over your object private fields values. for example if you don't wanna allow nulls or negative values for integers. Also, encapsulation is useful for triggering events on change of values of object members.
Example
another example
and also another implementation of read only properties could be as follows
您指的是属性还是关键字
get;设置;
?属性:简单地说,属性就是智能字段。聪明的是,当您想要获取或设置值时,您可以添加逻辑。用法示例:如果您想要验证为属性设置的值,或者如果您想要组合来自不同字段的值而不向公众公开这些字段。
关键字:这是创建带有支持字段(存储值的字段)的属性的 C# 简写。当您开始编写新代码并希望尽早完成界面时,它非常有用。
Did you mean just properties or the keywords
get; set;
?Properties: to put it easily, properties are smart fields. Smart being you can add logic when you want to get or set the value. Usage example: if you want to validate the values being set to a property or if you want to combine values from different fields without exposing those fields to the public.
The keywords: this is a C# shorthand to create a property with a backing field (the field that stores the values). It's useful when you're starting a new code and wanted to do the interface as early as possible.