C# 3.0 - 新功能 - Collection Initializers

Collection Initializers 即是透過前述的 Object Initializers,讓我們可以直接對物件做一或多次初始化動作。

        static List<Customer> CreateCustomers()
        {
            return new List<Customer>
                {
                    new Customer(1) { Name = "波羅實業",          City = "台北市" },
                    new Customer(2) { Name = "湯姆科技",          City = "台中市" },
                    new Customer(3) { Name = "墩墩數位",          City = "高雄市" },
                    new Customer(4) { Name = "摩利光電",          City = "新竹市" },
                    new Customer(5) { Name = "瑞之路邊攤",        City = "花蓮市" }
                };
        }    

 

完整範例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NewLanguageFeatures
{
    public class Customer
    {
        public int CustomerId { get; private set; }

        public string Name { get; set; }
        public string City { get; set; }

        public Customer(int Id)
        {
            CustomerId = Id;
        }

        public override string ToString()
        {
            return Name + "\t" + City + "\t" + CustomerId;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = CreateCustomers();

            Console.WriteLine("Customers:\n");
            foreach (Customer c in customers)
                Console.WriteLine(c);
        }

        static List<Customer> CreateCustomers()
        {
            return new List<Customer>
                {
                    new Customer(1) { Name = "波羅實業",          City = "台北市" },
                    new Customer(2) { Name = "湯姆科技",          City = "台中市" },
                    new Customer(3) { Name = "墩墩數位",          City = "高雄市" },
                    new Customer(4) { Name = "摩利光電",          City = "新竹市" },
                    new Customer(5) { Name = "瑞之路邊攤",        City = "花蓮市" }
                };
        }        

    }
}

執行結果:

Customers:

波羅實業        台北市  1
湯姆科技        台中市  2
墩墩數位        高雄市  3
摩利光電        新竹市  4
瑞之路邊攤      花蓮市  5
Press any key to continue . . .

筆者使用的環境:Windows 2008 RC0 English + Visual Studio 2008