ASP.NET3.5——匿名类型(Anonymous Types)

/// <summary>
/// CollectionInitializers(集合初始化器)的摘要说明
/// </summary>
public class CollectionInitializers
{
    public int ID { get; set; }
    public string Name { get; set; }

    public void CollectionInitializersTest()
    {
        List<CollectionInitializers> list = new List<CollectionInitializers>
        {
            new CollectionInitializers { ID = 1, Name = "webabcd" },
            new CollectionInitializers { ID = 2, Name = "webabcdefg" },
            new CollectionInitializers { ID = 3, Name = "webabcdefghijklmn" }
        };

        // 上面的list集合(集合初始化器)等同于下面的list集合

        // List<CollectionInitializers> list = new List<CollectionInitializers>();
        // list.Add(new CollectionInitializers { ID = 1, Name = "webabcd" });
        // list.Add(new CollectionInitializers { ID = 2, Name = "webabcdefg" });
        // list.Add(new CollectionInitializers { ID = 3, Name = "webabcdefghijklmn" });
    }
}

匿名类型允许定义行内类型,无须显式定义类型。常和var配合使用来声明匿名类型。

var p1 = new { Id = 1, Name = "YJingLee", Age = 22 };//属性也不需要申明
var p2 = new { Id = 2, Name = "XieQing", Age = 25 };
p1 = p2;//p1,p2结构相同,可以互相赋值

image

在这里编译器会认为p1,p2相当于:

public class SomeType
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

那么数组怎么定义呢?使用"new[]"关键字来声明数组,加上数组的初始值列表。像这样:

var intArray = new[] { 2, 3, 5, 6 };
var strArray = new[] { "Hello", "World" };
var anonymousTypeArray = new[] 
{ 
    new { Name = "YJingLee", Age = 22 }, 
    new { Name = "XieQing", Age = 25 } 
};
var a = intArray[0];
var b = strArray[0];
var c = anonymousTypeArray[1].Name;

image

匿名类型要点

  1. 可以使用new关键字调用匿名初始化器创建一个匿名类型的对象。
  2. 匿名类型直接继承自System. Object。
  3. 匿名类型的成员是编译器根据初始化器推断而来的一些读写属性。
原文地址:https://www.cnblogs.com/iceicebaby/p/1945624.html