C# 中的委派 (Delegation)

基礎篇

C# 簡介

開發環境

變數與運算

流程控制

陣列

函數

物件

例外處理

函式庫篇

檔案處理

資料結構

正規表達式

Thread

應用篇

視窗程式

媒體影音

網路程式

遊戲程式

手機程式

資料庫

雲端運算

特殊功能

委派

擴展方法

序列化

LinQ

WPF

網路資源

教學影片

投影片

教學文章

軟體下載

考題解答

101習題

委派

using System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);

class MainClass
{
    // Regular method that matches signature:
    static void SampleDelegateMethod(string message)
    {
        Console.WriteLine(message);
    }

    static void Main()
    {
        // Instantiate delegate with named method:
        SampleDelegate d1 = SampleDelegateMethod;
        // Instantiate delegate with anonymous method:
        SampleDelegate d2 = delegate(string message)
        {
            Console.WriteLine(message);
        };

        // Invoke delegate d1:
        d1("Hello");
        // Invoke delegate d2:
        d2(" World");
    }
}

事件

C#物件 事件 委派 撰寫 範例

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

namespace eventSimple
{
    class Program
    {

        delegate void myFunction(string text);
        static event myFunction readKeyEvent;

        static void Main(string[] args)
        {

            readKeyEvent += new myFunction(myFunction1);
            Console.WriteLine("請輸入一字串");
            string text = Console.ReadLine();
            Console.WriteLine();

            Console.WriteLine("第一次觸發事件");
            readKeyEvent.Invoke(text);
            Console.WriteLine();

            readKeyEvent += new myFunction(myFunction2);
            Console.WriteLine("請輸入一字串");
            text = Console.ReadLine();
            Console.WriteLine();

            Console.WriteLine("第二次觸發事件");
            readKeyEvent.Invoke(text);
            Console.WriteLine();

            Console.WriteLine("按任意鍵離開");
            Console.ReadKey();

        }

        static void myFunction1(string text)
        {
            Console.WriteLine("這次第一次執行的函數");
            Console.WriteLine("參數="+text);
        }

        static void myFunction2(string text)
        {
            Console.WriteLine("這次第二次執行的函數");
            Console.WriteLine("參數=" + text);
        }

      }
}

參考文獻

  1. C# 語言參考 - delegate (C# 參考)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License