C#委託(delegate)

libingql發表於2014-05-31

  C#中委託(delegate)是一種安全地封裝方法的型別,委託是物件導向的、型別安全的。

  使用委託的步驟:

  1、宣告委託

public delegate void DelegateHandler(string message);

  2、定義委託方法

// Create a method for a delegate.
public static void DelegateMethod(string message)
{
    Console.WriteLine(message);
}

  3、建立委託物件,並將需要傳遞的函式作為引數傳入

// Instantiate the delegate.
DelegateHandler handler = DelegateMethod;

  或:

// Instantiate the delegate.
DelegateHandler handler = new DelegateHandler(DelegateMethod);

  4、呼叫委託方法

// Call the delegate.
handler("Hello World");

  完整示例:

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

namespace DelegateExample
{
    class Program
    {
        public delegate void DelegateHandler(string message);

        public static void DelegateMethod(string message)
        {
            Console.WriteLine(message);
        }
    
        static void Main(string[] args)
        {
            //DelegateHandler handler = DelegateMethod;
            DelegateHandler handler = new DelegateHandler(DelegateMethod);
            handler("Hello World!");
        }
    }
}

 

相關文章