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/archive/2011/01/26/1945624.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值