2010年1月7日木曜日

delegateキーワードを使用してDelegateを定義し、その宣言とインスタンス化(Methodの登録)を同時に行ってみる。

using System;


// Delegateを定義
delegate void SampleDelegate(int n,string s);


class MainClass
{
    // Methodを定義
    static void method(int n,string s)
    {
        // 出力値 n:s
        Console.WriteLine("{0}:{1}",n,s);
    }


    static void Main()
    {
        /* SampleDelegate型の変数sdの宣言と
         * インスタンス化を同時に行ってみる */
        SampleDelegate sd1
            =new SampleDelegate(method);
        // さらにnewキーワードも省略してみる
        SampleDelegate sd2 = method;


        // 出力値:1:Sample1
        sd1(1,"Sample1");
        // 出力値:2:Sample2
        sd1(2,"Sample2");
        // 出力値:3:Sample3
        sd2(3, "Sample3");
        // 出力値:4:Sample4
        sd2(4, "Sample4");
    }
}

0 コメント:

コメントを投稿