c# 自动实现属性 隐式类型 对象及集合初始化 匿名类型

Demo 

using System;
using System.Collections.Generic;

namespace IntelligentCompiling
{
    class Program
    {
        static void Main(string[] args)
        {
            //隐式类型数组
            var array =new int[12, 23, 32];
            //隐式类型集合
            var list = new List<int>();
            //隐式类型变量
            var intVar = 3;

            //无需构造函数的初始化
            Person p = new Person { Name = "Daniel", Weight = 50 };

            //集合初始化
            var names = new List<string>()
            {
                "Alen","Bill","Carl","Daniel"
            };

            //匿名类型   = 隐式类型+对象初始化
            //匿名类型对象
            var people = new { Name = "Alen", Age = 15 };
            Console.WriteLine("{0}的年龄为{1}", people.Name, people.Age);
            //匿名类型数组
            var personCollection = new[]
            {
                new {Name="Tom",Age=20},
                new {Name="Ellen",Age=21},
                new {Name="Frank",Age=22}
            };
            int totalAge = 0;
            foreach(var per in personCollection)
            {
                totalAge += per.Age;
            }
            Console.WriteLine("Age total:" + totalAge);
            Console.Read();
        }
    }

    class Person
    {
        //定义可读写属性
        public string Name { get; set; }
        //定义只读属性
        public int Age { get;private set; }
        public int Weight { get; set; }
    }
}

猜你喜欢

转载自blog.csdn.net/u012664198/article/details/82856970
今日推荐