zoukankan      html  css  js  c++  java
  • 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. 匿名类型的成员是编译器根据初始化器推断而来的一些读写属性。
  • 相关阅读:
    python 序列的方法
    python函数基础
    Flume入门:安装、部署
    Flume日志收集系统介绍
    Python 列表(List)操作方法详解
    在linux下新增一块硬盘的操作。(包含大于2T的硬盘在linux下挂载操作)
    python字符串操作大全
    Python中的迭代器漫谈
    Linux 常用快捷键
    ssh采用expect实现自动输入密码登录、拷贝
  • 原文地址:https://www.cnblogs.com/iceicebaby/p/1945624.html
Copyright © 2011-2022 走看看