为参数对象创建常规类或内部类?
我没有将许多参数传递给一个方法,而是将其封装到一个参数对象中。
注意:简化演示
对于这种情况,更好的做法是什么?
• 创建一个类并将其命名为
InventorySaveArgs
?
-- 或 --
• 创建一个嵌套类并将其命名为SaveArgs
?
您能否解释一下为什么人们会选择其中之一?
[编辑]:该参数类型也将在其他程序集中使用。
附带问题:只是好奇,是否有一个模式名称可以偶然将多个参数封装到单个对象中。
[更新]:发现嵌套MSDN 上的类型使用指南InventorySaveArgs
应该可以从其他程序集中获得,因此我将使用常规类。
Instead of passing many arguments to a method, I was encapsulating it into an argument object.
note: simplied for demo
For such a case, what would be a better practice?
• Create a class and name it as
InventorySaveArgs
?
-- or --
• Create a nested class and name it asSaveArgs
?
And would you also explain why one would choose one or the other?
[EDIT]: That argument type will be used in another assemblies, as well.
side question: Just curious, if there is a pattern name for encapsulating multiple parameters to a single object by chance.
[UPDATE]: Found Nested Type Usage Guidelines on MSDNInventorySaveArgs
should be available from another assemblies, so I am going with a regular class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
IIRC .NET 设计指南对此非常明确 - 不应该有公共嵌套类型。
IIRC .NET Design Guidelines are pretty clear on this - there should be no public nested types.
我将其命名为
InventorySaveArgs
以防万一您想让该类型可供其他类型使用。 如果您从一开始就将其命名为InventorySaveArgs
,那么如果您需要重构,您将拥有一个在所有上下文中都有意义的名称。I would name it
InventorySaveArgs
just in case you ever want to make the type available to other types to use. If you name itInventorySaveArgs
from the beginning then you will have a name that is meaningful in all contexts if you ever need to refactor.我会选择第一个,创建一个外部类并将其命名为 InventorySaveArgs。 如果在公共方法中使用特定的类,则不将其包含在类之外的唯一论据是名称空间污染。
坦率地说,在 C# 中拥有内部类非常烦人,因为您必须不断地在类型名称前加上类的名称。 如前所述,一旦公开,这样做的唯一动机就是减少名称空间污染。 但是,如果您的命名空间太大,以至于 InventorySaveArgs 类使其太大,您可能无论如何都需要分解您的命名空间。
I would choose the first, create an outer class and name it InventorySaveArgs. If the particular class is used in a public method, the only argument for not including it outside the class is namespace pollution.
Having the inner class is quite frankly annoying in C# because you must constantly prefix the type name with the name of the class. As stated, once it's public the only motivation for donig this is reduction of namespace pollution. But if your namespace is so big that the InventorySaveArgs class is making it too big you probably need to break up your namespace anyways.
我听说过的将多个参数封装到单个对象的唯一模式是 详细的重构模式作者:马丁·福勒
The only pattern for encapsulating multiple parameters to a single object I've ever heard of is a refactoring pattern detailed by Martin Fowler