在C#中匿名类型

在C#中匿名类型

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

问题描述

    // x is compiled as an int
    var x = 10;

   // y is compiled as a string
   var y = "Hello";

   // z is compiled as int[]
   var z = new[] { 0, 1, 2 };



but

   // ano is compiled as an anonymous type
   var ano = new { x1 = 10, y1 = "Hello" };



ANO 创建的对象的属性为只读。我想弄清楚,为什么这些属性是只读的。 ?建议是值得赞赏的。

ano object's properties created are read-only . I want to figure it out why those properties are read only. suggestions are appreciated ?

编辑:

var ano1 = new { x1 = 10, y1 = "Hello" };

var ano2 = new { x1 = 10, y1 = "Hello" };



时,如果新的匿名类型具有属性的以相同的顺序相同的数量和类型将它相同的内部类型的第一个?

Is that if the new anonymous type has the same number and type of properties in the same order will it be of the same internal type as the first ?

推荐答案

VAR 做不是说使用匿名类型,意思是的编译器,去搞清楚类型我!。在前三种情况下,类型实际上是一个命名类型 - System.Int32 System.String ,和 System.Int32 [] (在最后一种情况下数组元素的类型也由你把在初始化数组元素的类型,编译器推断)。

var does not mean "use an anonymous type", it means "Compiler, go figure out the type for me!". In the first three cases, the type is actually a "named" type - System.Int32, System.String, and System.Int32[] (in the last case the type of array's elements is also deduced by the compiler from the type of array elements that you put in the initializer).

最后一种情况是唯一一个在使用匿名类型。它是由设计,C#的匿名类型的一成不变的。在第一个地方添加它们在语言中的主壳体已经介绍LINQ,当匿名类型产生不需要的情况下可变性的。一般情况下,一成不变的类往往给设计师少的问题,尤其是当并发涉及,所以语言的设计者决定去与不可变匿名类型。

The last case is the only one where an anonymous type is used. It is by design that C#'s anonymous types are immutable. The primary case for adding them in the language in the first place has been introduction of LINQ, which does not need mutability in cases when anonymous types are produced. In general, immutable classes tend to give designers less problems, especially when concurrency is involved, so designers of the language decided to go with immutable anonymous types.

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

08-22 13:02