C#7中的C#匿名类型是否冗余 [英] Are C# anonymous types redundant in C# 7

查看:102
本文介绍了C#7中的C#匿名类型是否冗余的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自C#7引入值元组以来,是否存在有意义的场景,它们比元组更适合?

Since C# 7 introduces value tuples, is there a meaningful scenario where they are better suited than tuples?

例如,以下行

collection.Select((x, i) => (x, i)).Where(y => arr[y.i].f(y.x)).ToArray();

进行以下一行

collection.Select((x, i) => new {x, i}).Where(y => arr[y.i].f(y.x)).ToArray();

多余.

一个用例比另一个用例(出于性能原因或优化目的)更好的用例是什么?

What would be the use case where one is better used over the other (for either performance reasons or optimization)?

很明显,如果需要六个以上的字段,则不能使用元组,但是还有一些细微差别吗?

Obviously, if there is a need for more than six fields, tuples cannot be used, but is there something a bit more nuanced to it?

推荐答案

匿名类型和C#7元组之间存在各种差异,在某些情况下,它们可能比另一种更合适:

There are various differences between anonymous types and C# 7 tuples, which may or may not make one more appropriate than the other in certain situations:

  • C#7个元组是ValueTuple<>个.这意味着它们是值类型,而匿名类型是引用类型.
  • 由于组合键是可以显式表示的类型,因此它们允许在编译时进行静态键入.这样,您可以将它们用作方法参数,返回类型等.
  • 匿名类型的成员是该类型上存在的实际属性.元组项目是字段.
  • 匿名类型的属性具有实际名称,而元组上的字段仅被命名为ItemN(对于数字N).标签只是主要由编译器使用的元数据信息,并不与实际的元组对象一起保留.
  • 由于创建匿名类型实际上是在幕后创建了一个类型,因此它们具有一定的类型安全性.由于元组只是具有应用类型参数的通用容器,因此您不具有完整的类型安全性.例如, size (int, int)元组与 position (int, int)元组完全兼容,而匿名类型被完全封闭.
  • 正如Jon Skeet所述,C#7元组语法在表达式中为目前不支持树木.
  • C# 7 tuples are ValueTuple<>s. That means they are value types while anonymous types are reference types.
  • Tuples allow static typing at compile time since they are a type that can be expressed explicitly. As such, you can use them as method arguments, return types, etc.
  • Members of an anonymous type are actual properties that exist on the type. Tuple items are fields.
  • The properties of an anonymous type have an actual name, while the fields on a tuple are just named ItemN (for numbers N). The labels are just metadata information that is mostly used by the compiler, and is not persisted with the actual tuple object.
  • Because creating an anonymous type actually creates a type under the hood, you have a level of type safety with them. Since tuples are just generic containers with applied type arguments, you do not have full type safety with them. For example an (int, int) tuple for a size would be fully compatible to an (int, int) tuple for a position, while anonymous types are closed off completely.
  • As Jon Skeet mentioned, the C# 7 tuple syntax is currently not supported in expression trees.

这篇关于C#7中的C#匿名类型是否冗余的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆