1

我是 C# 新手。当我们声明这样的语句时

var list = new { FirstName = "Jon", LastName ="Doz" }; .

我没有在声明中提供任何类型。编译器如何在不抛出错误的情况下接受它。

我是说new <without type>

4

5 回答 5

4

它被称为匿名类型

C# 编译器在后台将其转换为更详细的声明,例如:

class __Anonymous1
{
   private string firstName ;
   private string lastName;
   public string FirstName{get { return firstName; } set { firstName = value ;} }
   public string LastName{ get { return lastName; } set { lastName= value ; } }
}
__Anonymous1 list = new __Anonymous1();
list.FirstName = "Jon";
list.LastName ="Doz";
于 2013-06-29T05:02:29.273 回答
2

它实际上是在创建一个匿名类型,一种只有您声明的那些字段的临时类。

请注意,这var不是这样做的。var只是进行类型推断,所以你可以说它var list = new List<int>();不会创建匿名类型。它new {...}负责临时类的创建。但是,使用var是将其存储在变量中的唯一方法,因为匿名类型没有名称。

于 2013-06-29T05:01:27.787 回答
0

这称为匿名类型。它只是一个属于没有名称的类型的对象,并且具有您给它的这两个属性。

您可以在此处阅读有关匿名类型的更多信息:

http://msdn.microsoft.com/en-us/library/vstudio/bb397696.aspx

于 2013-06-29T05:01:57.983 回答
0

As @IanHenry stated, you are creating an Anonymous Type. They were created to support LINQ and are readonly. This means if you create an anonymous type like the one in your question, you cannot update any of the values.

于 2013-06-29T05:03:15.257 回答
0

This concept is knows as Anonymous Types. From MSDN:

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

于 2013-06-29T05:04:23.250 回答