假设我有一个名为 Composite
的类,其中包含另一个类 Component
的集合,所有类都有一个属性 Name
。使用Dictionary
来存储组件会更好,还是使用动态对象会更好。
例如,这样做会更好吗:
Component component = someComposite.Components["RandomComponent"];
或者这个:
Component component = someComposite.Components.RandomComponent;
其中,第二个示例中的 someComposite.Components 是动态
。
第二种情况似乎更好,但没有类型安全...
我想补充一点,在某个时候我最终会这样做:
DerivedComponent component = someComposite.Components["RandomComponent"] as DerivedComponent;
在这种情况下,dynamic
可以节省我输入转换的时间。
那么哪个设计更好呢?
Say I have a class called Composite
which contains a collection of another class Component
, all of which have a property Name
. Would it be better to use a Dictionary
to store the components, or would it be better to use a dynamic object.
For example, would it be better to do this:
Component component = someComposite.Components["RandomComponent"];
or this:
Component component = someComposite.Components.RandomComponent;
Where someComposite.Components is dynamic
in the second example.
The second case seems to be nicer, but there's no type safety...
I want to add that at some point I will end up doing this:
DerivedComponent component = someComposite.Components["RandomComponent"] as DerivedComponent;
In which case dynamic
can save me typing out the conversion.
So which is better design?
发布评论
评论(2)
也许只有我这么认为,但我认为动态更多地是处理 COM 互操作以及与 IronPython 等动态语言交互的便捷方式。
dynamic
实际上不应该在全 C# 程序中使用。使用字典<字符串、组件>。
并查看 System.ComponentModel (即 IContainer 和 IComponent 接口)。
Maybe it's just me, but I see
dynamic
more as an convenient way to deal with COM interop and to interact with dynamic languages such as IronPython.dynamic
shouldn't really be used in an all-C# program.Use a Dictionary<string, Component>.
And have a look at System.ComponentModel (i.e. the IContainer and IComponent interfaces).
在静态类型语言中,这些类型的存在是有原因的;不要因为必须添加一些额外的语法而将它们扔掉。该语法是作为警告 - “嘿!我在这里做的事情不是类型安全的!”
最终,这一切都归结为成本与收益。您可以享受类型安全、静态调用、重构时为您提供帮助的 IDE 等额外好处……或者您可以节省一点打字时间(这有点像文档)。
此外,您必须考虑错误条件。使用
动态
,如果对象不包含该定义,您的错误代码将如下所示:与以下内容相比:
看起来您实际上并没有节省那么多打字时间。
In a statically-typed language, those types are there for a reason; don't just throw them out because of a little bit of extra syntax you have to put. That syntax is there as a warning -- "Hey! I'm doing something that is not type-safe here!"
In the end, it all comes down to cost vs. benefits. You can either have the added benefit of type safety, static invocation, the IDE helping you when you refactor...or you can save yourself a tiny bit of typing (which is kind of like documentation).
Furthermore, you have to think about error conditions. With a
dynamic
, your code on errors will look like this if the object does not contain that definition:Compared with:
That does not appear that you're actually saving yourself that much typing.