首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 委派進階:實例方法綁定、多點廣播、事件處理機制完整實作

     編輯:關於C語言

委派綁定實例方法

靜態方法無需物件參考;實例方法需提供物件:

MathClass obj = new MathClass();
myDelegate Operation = new myDelegate(obj.Power);

完整範例

using System;

public class DelegateClass
{
    delegate long myDelegate(int i, int j);

    public static void Main(string[] args)
    {
        MathClass mathObj = new MathClass();
        myDelegate Operation = new myDelegate(mathObj.Add);
        Console.WriteLine("Call to Add method through delegate");
        long l = Operation(10, 20);
        Console.WriteLine("Sum of 10 and 20 is " + l);

        Console.WriteLine("Call to Multiply method thru delegate");
        Operation = new myDelegate(mathObj.Multiply);
        l = Operation(1639, 1525);
        Console.WriteLine("1639 multiplied by 1525 equals " + l);
    }
}

委派與事件:多點廣播機制

  • 事件 = event 關鍵字 + 委派型別欄位
  • 支援多個處理函式(+=/-= 訂閱/退訂)
  • 只有宣告事件的類別能引發事件

事件實作範例

public delegate void CustomEventHandler(object sender, EventArgs e);
public event CustomEventHandler CustomEvent;
using System;

class TestClass
{
    static void Main(string[] args)
    {
        EventClass myEventClass = new EventClass();
        myEventClass.CustomEvent += new EventClass.CustomEventHandler(CustomEvent1);
        myEventClass.CustomEvent += new EventClass.CustomEventHandler(CustomEvent2);
        myEventClass.InvokeEvent();
        myEventClass.CustomEvent -= new EventClass.CustomEventHandler(CustomEvent2);
        myEventClass.InvokeEvent();
    }

    private static void CustomEvent1(object sender, EventArgs e)
        => Console.WriteLine("Fire Event 1");

    private static void CustomEvent2(object sender, EventArgs e)
        => Console.WriteLine("Fire Event 2");
}

public class EventClass
{
    public delegate void CustomEventHandler(object sender, EventArgs e);
    public event CustomEventHandler CustomEvent;

    public void InvokeEvent()
        => CustomEvent(this, EventArgs.Empty);
}

輸出:

Fire Event 1
Fire Event 2
Fire Event 1
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved