1. 程式人生 > >c# 自動實現屬性 隱式型別 物件及集合初始化 匿名型別

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; }
    }
}