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. 匿名类型的成员是编译器根据初始化器推断而来的一些读写属性。
  • 相关阅读:
    codeforces 869E. The Untended Antiquity(二维树状数组,随机化)
    bzoj 3083: 遥远的国度(树上换根操作,树剖+询问整个子树)
    hdu 5534 Partial Tree(dp+降唯,好题)
    AtCoder Regular Contest 075 E
    hihocoder 1387 A Research on "The Hundred Family Surnames"(树,lca,求同一颜色的直径)
    hdu 5458 Stability(生成树,树链剖分,好题)
    推荐一套个人ui组件库
    回望2019,期盼2020
    如何从产品的角度对待自己的博客
    致一名迷茫的我
  • 原文地址:https://www.cnblogs.com/iceicebaby/p/1945624.html
Copyright © 2011-2022 走看看