.NET 中自动属性的用途

发布于 2024-09-12 14:19:41 字数 184 浏览 3 评论 0原文

为什么是这样:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小情绪 2024-09-19 14:19:41

因为您可以透明地(从客户端代码的角度)更改 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.

三生殊途 2024-09-19 14:19:41

字段的目的是对象状态存储,而属性的目的仅仅是访问。这种差异可能更多的是概念性的而不是实际性的,但自动属性提供了一种方便的语法来声明两者。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文