在C# 2.0中,加入泛型的功能。以往在1.X版中,使用堆疊、佇列等資料結構,只能用object型態,並沒辦法把型態固定下來,使得資料中摻雜一種以上的資料型態。一不注意,程式就容易發生Runtime的錯誤。幸好在2.0中,這些的問題獲得改善。

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

namespace ConsoleApplication1
{
    delegate void Function(int x);
    class Program
    {
        static void myFunction(Function f)
        {
            f(6);  
        }
       
        static void Main(string[] args)
        {
            Console.WriteLine("以下是泛型的執行結果");
            Stack<int> myStack = new Stack<int>();

            for (int i = 0; i < 10; i++)
            {
                myStack.Push(i);
            }

            foreach (int i in myStack)
                Console.WriteLine(i);
       
            Console.WriteLine("以下是匿名函數的用法");
            myFunction(delegate(int x){Console.WriteLine("印出:" + x);});
            myFunction(delegate(int x) { Console.WriteLine("印出:" + (x + 2)); });
           
            Function a = new Function(delegate(int x) { Console.WriteLine("第一個"); });
            a += delegate(int x) { Console.WriteLine("第二個"); };
            a += delegate(int x) { Console.WriteLine("第三個,並印出X:"+x.ToString()); };
            a(3);
           
           
        }
    }
}

從上面的程式碼,我們看到:

        Stack<int> myStack = new Stack<int>();

在1.X版中,是沒辦法用<>指定型態,在2.0中,我們可以在一些的常見資料結構中指定型態,減少Runtime上的錯誤。上例中,如果加入像"myStack.Push(6.11)"這一行的程式碼,編譯器就會產生編譯錯誤,這樣的好處就在程式的bug在程式人員這邊就可以發現,而不是到了測試人員甚至是使者用那邊才被發現。

另外在2.0版中,還加入了匿名函數的功能,也就是能將程式碼當作參數。

    delegate void Function(int x);
    class Program
    {
        static void myFunction(Function f)
        {
            f(6);  
        }
    }........(略)

假設在一個函式中,想將部份的功能交給別人去作,可以使用delegate型態。上面的Function函數將回傳設為void,參數為一個int的x。這樣的作法,在於只需將規格訂好,剩下內部的實作,就交給其它應該負責的人去作就好了。而在myFunction中,使用到一次f參數,f內部怎麼作,不需要知道,只要在使用時,記得將程式碼加進去就好了。

            myFunction(delegate(int x){Console.WriteLine("印出:" + x);});
            myFunction(delegate(int x) { Console.WriteLine("印出:" + (x + 2)); });

上面的程式碼,第一個會將變數x印出,第二個則是將x加2之後再印出。除此之外,匿名函數還有另一種用法:

            Function a = new Function(delegate(int x) { Console.WriteLine("第一個"); });
            a += delegate(int x) { Console.WriteLine("第二個"); };
            a += delegate(int x) { Console.WriteLine("第三個,並印出X:"+x.ToString()); };
            a(3);

a變數在宣告時,已經加入了一行程式碼,或者說是一個函數,之後再加入兩個函數。執行a的時候,是加入幾個函數就執行幾個函數,並不會有衝突。 

C# 2.0另外兩個新功能,在下期的文章會提到,另外也會補充泛型與匿名函數的內容。


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 卑微研究生 的頭像
    卑微研究生

    卑微研究生的部落格

    卑微研究生 發表在 痞客邦 留言(0) 人氣()