简体   繁体   English

C#中匿名类型的性能

[英]Performance of anonymous types in C#

C#中使用匿名类型是不是很糟糕?

No, it is not. 不它不是。 They are code generated classes at compiletime and perform as well as normal classes. 它们是在编译时生成的代码类,并且与普通类一样执行。

They're like other types, in terms of performance. 就性能而言,它们就像其他类型一样。

edit 编辑

To be more clear, I should have said that they perform exactly like other types because they are exactly like other types, except for the fact that the compiler generates the name. 更清楚的是,我应该说它们的表现与其他类型完全相同,因为它们与其他类型完全相同,除了编译器生成名称的事实。 The only way performance would suffer is if you pass an instance of the anonymous type to another scope, where reflection or dynamic would have to be used just to access the properties. 性能受到影响的唯一方法是将匿名类型的实例传递给另一个范围,其中只需使用反射或dynamic来访问属性。 That would be expensive because it involves late binding to resolve everything at runtime. 这将是昂贵的,因为它涉及后期绑定以在运行时解决所有问题。

Are anonymous types in themselves bad? 匿名类型本身是不是很糟糕? No. If they were the C# team certainly wouldn't have wasted their time adding it to the language. 不。如果他们是C#团队,那么肯定不会浪费时间将它添加到语言中。 Under the hood they just compile down to standard CLR types. 在引擎盖下,他们只需编译成标准的CLR类型。

Can anonymous types, like practically every other language feature, be abused to the point of being non-performant. 匿名类型,例如几乎所有其他语言特征,都可以被滥用到不具备性能的程度。 Sure. 当然。

An anonymous type in C# is still a static type and accessing its methods and properties is resolved by the compiler. C#中的匿名类型仍然是静态类型,并且编译器会解析访问其方法和属性的问题。 The performance is comparable to explicit types. 性能与显式类型相当。

It's not bad, sometimes it is convinient. 它不错,有时它很方便。 For example, when using Linq, instead of creating a class that will be used only once, it's preferable to use anonymous types. 例如,在使用Linq时,不是创建只使用一次的类,而是使用匿名类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM