一个简单而简洁definiton和匿名类型说明在C#中? [英] A simple and succinct definiton and explanation of anonymous types in C#?
问题描述
我不知道什么是匿名类型是在C#也不是如何使用的。 ?可以somone给我这一个很好的说明,它的使用
I have no clue what an "anonymous type" is in C# nor how it is used. Can somone give me a good description of it and it's use?
[注:我真的知道它是什么,以及如何使用它,但想到我会问那些不这样做]
[Note: i really know what it is and how to use it but thought i'd ask for those that don't]
推荐答案
这是匿名类型是由编译器生成的类型,由于这样的表达式:
An anonymous type is a type generated by the compiler due to an expression such as:
new { Property1 = x.Value1, Property2 = y.Value2, z.Value3 }
(最后一个是像 =值3 z.Value3
)。
匿名类型的名称是难以启齿 - 即你不能在普通的C#指定它 - 但它是一个完全正常的类型至于CLR而言。正如你不能写名字,如果你想创建一个匿名类型的变量(或使用匿名类型作为类型参数泛型类型),您需要使用的隐式类型的局部变量与 VAR
关键字:
The name of the anonymous type is "unspeakable" - i.e. you can't specify it in normal C# - but it's a perfectly normal type as far as the CLR is concerned. As you can't write the name, if you want to create a variable of an anonymous type (or a generic type using an anonymous type as the type argument), you need to use an implicitly typed local variable with the var
keyword:
var person = new { Name = "Bill", Address = "..." };
C#匿名类型是不可变的(即属性是只读) - 生成的类型有单构造函数取值为所有属性作为参数。该物业类型从数值推断出来的。
C# anonymous types are immutable (i.e. the properties are read-only) - the generated type has a single constructor which takes values for all the properties as parameters. The property types are inferred from the values.
匿名类型覆盖的GetHashCode
,等于
和的ToString
在相当明显的方式 - 默认的相等比较每个属性类型用于哈希和平等
Anonymous types override GetHashCode
, Equals
and ToString
in reasonably obvious ways - the default equality comparer for each property type is used for hashing and equality.
它们通常在LINQ使用,你会使用选择值1作为Property1,值2作为Property2,值3在SQL以同样的方式。
They are typically used in LINQ in the same way that you'd use "SELECT Value1 As Property1, Value2 As Property2, Value3" in SQL.
它使用了相同的顺序将指向同一类型相同的属性名称和类型,所以你可以写的每一个匿名类型初始化表达式:
Every anonymous type initializer expression which uses the same property names and types in the same order will refer to the same type, so you can write:
var x = new { Name = "Fred", Age = 10 };
x = new { Name = "Bill", Age = 15 };
这也是值得了解VB匿名类型稍有不同:在默认情况下,他们是可变的。您可以使用钥匙关键字使每单个属性不变。我个人比较喜欢C#的方式,但我可以看到易变性是在某些情况下非常有用。
It's also worth knowing that VB anonymous types are slightly different: by default, they're mutable. You can make each individual property immutable using the "Key" keyword. Personally I prefer the C# way, but I can see mutability being useful in some situations.
这篇关于一个简单而简洁definiton和匿名类型说明在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!