C# 3.0 - 新功能 - implicit Type

C# 3.0 允許區域變數(local variable)使用 var 來宣告變數,它並不是以前 VB 6 的那個 var。

當使用 var 宣告時,CLR 會在編譯階段,由實際的值(等號右邊的值)來判斷它是屬於那個型態

使用以下範例來說明:

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

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

            Console.WriteLine();

            var vInt = 168;
            var vString = "這是字串";
            var x = new[] { 1, 2, 3 };

            Console.WriteLine("vInt : {0}", vInt);
            Console.WriteLine("vString : {0}", vString);
            foreach(var a in x)
                Console.WriteLine(a);
        }

執行結果:

Customers:

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

vInt : 168
vString : 這是字串
1
2
3
Press any key to continue . . .

 

完整範例:

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)
            foreach (var c in customers)
                Console.WriteLine(c);

            Console.WriteLine();

            var vInt = 168;
            var vString = "這是字串";
            var x = new[] { 1, 2, 3 };

            Console.WriteLine("vInt : {0}", vInt);
            Console.WriteLine("vString : {0}", vString);
            foreach(var a in x)
                Console.WriteLine(a);
        }

        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 = "花蓮市" }
                };
        }        

    }
}

這個功能筆者很喜歡,如果要學習 LINQ 的朋友,建議對於 C# 3.0 語言的新功能先了解一下。

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