Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Đa phát delegate (Multicasting Delegates) trong C#

Delegate giữ tham chiếu đến nhiều phương thức gọi là multicast delegate.

Ví dụ

using System;

delegate void myDelegate(int val1, int val2);

public class Demo {
    public static void CalAdd(int val1, int val2) {
        Console.WriteLine("{0} + {1} = {2}", val1, val2, val1 + val2);
    }
    public static void CalSub(int val1, int val2) {
        Console.WriteLine("{0} - {1} = {2}", val1, val2, val1 - val2);
    }
}

public class Program {
    static void Main() {
        myDelegate d = new myDelegate(Demo.CalAdd);
        d += new myDelegate(Demo.CalSub);
        d(45, 70);
        d -= new myDelegate(Demo.CalAdd);
        d(95, 70);
        d += new myDelegate(Demo.CalSub);
        d(88, 6);
        d -= new myDelegate(Demo.CalAdd);
        d(40, 20);
        Console.Read();
    }
}

Delegate: delegate void myDelegate(int val1, int val2);

Gán nhiều phương thức: d += new myDelegate(Demo.CalSub);, gỡ bỏ: d -= new myDelegate(Demo.CalAdd);