在 C# 中使用访问器的优点和缺点是什么
可能的重复:
公共变量与带有访问器的私有变量
我目前正在构建一个小型应用程序管理 XML 文件。每个条目在代码中都由自定义类的实例表示。现在要设置和获取属性,我可以允许直接访问它们,也可以使用访问器。哪一个更好,为什么?
Possible Duplicate:
public variables vs private variables with accessors
I am currently building a small application to manage an XML file. Each entry is represented in the code by an instance of a custom class. Now to set and get the properties, I can either allow direct access to them, or use accessors. Which one would be better, and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用或不使用访问器没有优缺点:您必须使用它们。
这只是一个 OOP 原则:封装对类字段或计算值的访问,这样它们的使用者就不会关心如何检索或分配某个值。
为什么?因为封装。这是 OOP 最重要的原则之一,因为这确保了在单个点中检索和分配值的方式。
There're no pros and cons of using accessors or not: you must use them.
It's just an OOP principle: encapsulate the access to the class fields or calculated values so consumers of them won't care about how some value is retrieved or assigned.
Why? Because of encapsulation. It's one of most important principles of OOP, since this ensures the way a value is retrieved and assigned in a single point.
优点:
属性:
一般来说,我总是在任何重要的类上使用它们。至少我会使用自动属性。
Pros:
Cons:
In general, I'd always use them on any significant class. At least I'll be using auto properties.
在这种特定场景中,访问器的明显优点是您可以限制仅对那些对您的 XML 架构有效的属性和子级进行访问(假设架构存在,应该如此,因为您控制着 XML)。这将由 setter 实现,但 getter 也将帮助您减少一点输入。
In this specific scenario, the obvious advantage of accessors is that you can limit access to only those properties and children that are valid for your XML schema (assuming that a schema exists, which should be so because you are in control of the XML). This will be implemented by the setters, but the getters will also help you reduce typing a bit.
访问器让您将来可以更改底层的工作方式...也许您更改 XML 架构或完全放弃 XML...您可以修改访问器实现,以便调用您的类的任何代码都可以保持原样。
不使用访问器的唯一好处是您需要维护的代码行数更少。
一定要使用访问器在类之间共享内容。
Accessors let you in the future change how things work under the hood... maybe you change the XML schema or ditch XML altogether... you could modify the accessor implementation so that any code calling your class can remain as-is.
The only benefit of not using accessors is that you then have a few less lines of code to maintain.
Definitely use accessors for sharing things between classes.