新文章

2012年8月23日 星期四

[C#]委託實作練習

用列印作為範本,實作一個委託的練習:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1_0823
{
    //宣告一個委託類型 PrintCompleteCallback
    public delegate void PrintCompleteCallback(string msg);
    
    class worker
    {
        //Class Printer變數
        Printer printer1, printer2, printer3;
        public void DoWork()
        {
            // _name="no.1"
            printer1 = new Printer("no.1");
            printer2 = new Printer("no.2");
            printer3 = new Printer("no.3");
 
            //宣告委託PrintCompleteCallback 的變數 callback ,參考class Printer的方法Notify
            PrintCompleteCallback callback = new PrintCompleteCallback(Printer.Notify);
 
            //參數callback是執行完Print,讓callbackGG去呼叫的委託
            printer1.Print(callback);
            printer2.Print(callback);
            printer3.Print(callback);
 
        }
        public static void Main()
        {
            worker work = new worker();
            work.DoWork();
            Console.ReadLine();
        }
    }
 
    class Printer
    {
        private string _name;
        public Printer(string name)
        {
            _name = name;
        }
 
        //委託類型的參數:用在工作完成後讓callbackGG去呼叫的委託callback,呼叫委託callback後喚醒Notify
        public void Print(PrintCompleteCallback callbackGG)
        {
            callbackGG(string.Format("{0} is done", _name));
        }
        public static void Notify(string message)
        {
            System.Console.WriteLine(message+"\n");
        }
 
    }
}

沒有留言:

張貼留言