ใช้คีย์เวิร์ด new เพื่อสร้าง Delegate Instance รูปแบบการส่งอาร์กิวเมนต์คล้ายการเรียกเมธอด แต่ไม่ต้องส่งพารามิเตอร์
ตัวอย่าง:
public delegate void printString(string s); printString ps1 = new printString(WriteToScreen);
สามารถสร้าง Delegate ด้วย Anonymous Method ได้:
delegate void Del(string str);
Del d = delegate(string name) {
Console.WriteLine("Notification received for: {0}", name);
};
ตัวอย่าง
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) { num += p; return num; }
public static int MultNum(int q) { num *= q; return num; }
public static int getNum() { return num; }
static void Main(string[] args) {
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
ผลลัพธ์
Value of Num: 35 Value of Num: 175