.NET 中自动属性的用途
为什么是这样:
public string Foo {get;set;}
比这更好:
public string Foo;
我一辈子都无法解决这个问题。任何人都可以透露一些信息吗?
谢谢
Why is this:
public string Foo {get;set;}
considered better than this:
public string Foo;
I can't for the life of me work it out. Can anyone shed some light?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为您可以透明地(从客户端代码的角度)更改 setter/getter 的实现,但如果您直接公开底层属性(因为它不兼容二进制),则您不能这样做
。不过,自动属性使您可以轻松地公开类状态的某些部分,而无需再三考虑。 Java 也遇到了这种情况,在许多项目中,您会发现
get/setXxx
对到处都暴露了内部状态(通常不需要它,“以防万一”),这会渲染属性本质上是公开的。Because you can transparently (from client code's perspective) change the implementation of the setter/getter wheras you cannot do the same, if you expose the underlying property directly (as it would not be binary compatible.)
There is a certain code smell associated with automatic properties, though, in that they make it far to easy to expose some part of your class' state without a second thought. This has befallen Java as well, where in many projects you find
get/setXxx
pairs all over the place exposing internal state (often without any need for it, "just in case"), which renders the properties essentially public.字段的目的是对象状态存储,而属性的目的仅仅是访问。这种差异可能更多的是概念性的而不是实际性的,但自动属性提供了一种方便的语法来声明两者。
While the purpose of a field is object state storage, the purpose of a property is merely access. The difference may be more conceptual than practical, but automatic properties provides a handy syntax for declaring both.