February 21st, 2009 | |
Posted in c#
Delegate with a simple example. Ref This link!
Delegate เป็น Pointer to Method เหมือนกับ การเอา Method ไปเก็บไว้ในตัวแปร เพื่อว่าให้เราสามารถเรียกที่ใช้ที่ไหนก็ได้ หรือจะส่งเป็น parameter ไปไห้ method อื่นก็ได้
Delegate เป็น type ชนิดพิเศษ ที่ใช้ในการเก็บการอ้างอิงไปยัง method(ทางอ้อม)
Delegate ช่วยให้Objectสามารถเรียกหา หรือ callback ไปยัง code ที่ใช้งานมันเพื่อดำเนินการบางอย่าง
Sample 1|Steps to create and call a delegate:
1. สร้าง delegate. delegate สามารถสร้างโดยใช้ keyword ‘delegate’ ตามด้วย return type แล้วตั้งชื่อ
public delegate int simpleDelegate (int a, int b);
2. กำหนด method ที่มี signature(parameter) แบบเดียวกับ delegate
public int addNumber(int a, int b)
public int mulNumber(int a, int b)
3. สร้าง สร้างที่จะเรียก method ที่ใช้ delegates.
using System;
class clsDelegate
{
public delegate int simpleDelegate (int a, int b);
public int addNumber(int a, int b)
{
return (a+b);
}
public int mulNumber(int a, int b)
{
return (a*b);
}
static void Main(string[] args)
{
clsDelegate clsDlg = new clsDelegate();
simpleDelegate addDelegate = new simpleDelegate(clsDlg.addNumber);
simpleDelegate mulDelegate = new simpleDelegate(clsDlg.mulNumber);
int addAns = addDelegate(10,12);
int mulAns = mulDelegate(10,10);
Console.WriteLine(“Result by calling the addNum method using a delegate: {0}”,addAns);
Console.WriteLine(“Result by calling the mulNum method using a delegate: {0}”,mulAns);
Console.Read();
}
}
Sample 2|
using System;
delegate void MyDelegate(string s);
class MyClass
{
public static void Hello(string s)
{
Console.WriteLine(“ Hello, {0}!”, s);
}
public static void Goodbye(string s)
{
Console.WriteLine(“ Goodbye, {0}!”, s);
}
public static void Main()
{
MyDelegate a, b, c, d;
a = new MyDelegate(Hello);
b = new MyDelegate(Goodbye);
c = a + b; // call ทั้ง 2 method
d = c – a; // เหลือ call b method เดียว
Console.WriteLine(“Invoking delegate a:”); a(“A”);
Console.WriteLine(“Invoking delegate b:”); b(“B”);
Console.WriteLine(“Invoking delegate c:”); c(“C”);
Console.WriteLine(“Invoking delegate d:”); d(“D”);
}
}
//======OutPut=====
//Invoking delegate a:
//Hello, A!
//Invoking delegate b:
//GoodBye, B!
//Invoking delegate c:
//Hello, C!
//GoodBye, C!
//Invoking delegate d:
//GoodBye, D!
Ref: ที่นี่ครับบทความดีๆอีกเยอะเลย TwoGuRU
Tags:
c#,
delegate,
microsoft,
programming