デリゲート理解(c# Action )

c#

以前にも書いた気がするけどcのポインターのポインターみたいで頭が混乱する。delegateに意味は分かった気は・・・する。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace delege03
{
    public class Test1
    {
        //Test2を作成しMethodを実行する
        public void Method()
        {
            Test2 test2 = new Test2();
            Action delagateMethod = delegateMethod1;
            delagateMethod += delegateMethod2;
            delagateMethod += delagateMethod3;
            test2.Method(delagateMethod); 
        }
        //Test2の処理が終わったら呼ばれる
        Action delegateMethod1 =() => Console.WriteLine("1:処理終わったよー");
        Action delegateMethod2 =() => Console.WriteLine("2:処理終わったよー");
        Action delagateMethod3 =() => Console.WriteLine("3:最後だよ~");
    }

    public class Test2
    {
        //引数及び返り値のないデリゲート
        //public delegate void Delegate();

        //何らかの処理をした後、入力されたデリゲートを実行する
        public void Method(Action delegateMethod)
        {
            /*処理*/
            Thread.Sleep(2000);
            delegateMethod();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test1 ts1 = new Test1(); //-- ここでインスタンスを生成
            Console.WriteLine("開始");

            ts1.Method();//-- ここでtest2を delegate してメソッドをコールバックする
            Console.WriteLine("$>");
            Console.ReadKey();
        }
    }
}
No tags for this post.
タイトルとURLをコピーしました