C# 中的委派

作品

書籍

課程

程式集

小說集

論文集

散文集

影片集

編輯雜誌

程式人

電子書

JavaScript

計算語言學

微積分

Blender 動畫

C# 語言

系統程式

高等 C 語言

Java

Android

Verilog

Wikidot

R 統計軟體

機率統計

計算機數學

組合語言

人工智慧

開放原始碼

網路資源運用

計算機結構

相關訊息

常用工具

友站連結

在家教育

RSS

最新修改

網頁列表

簡體版

English

委派

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# 參考)

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License