Anonymous Method คืออะไร?
Anonymous Method (เมธอดไร้ชื่อ) คือบล็อกโค้ดที่ส่งผ่านเป็นพารามิเตอร์ให้ Delegate โดยไม่ต้องประกาศเป็นเมธอดแยกต่างหาก มีแค่ Body (บอดี้) ไม่มีชื่อ
รูปแบบการประกาศ
delegate void DemoMethod(int n);
// สร้าง delegate จาก anonymous method
DemoMethod dm = delegate(int a)
{
Console.WriteLine("Anonymous Method ของเรา: {0}", a);
};
ตัวอย่างโค้ดสมบูรณ์
using System;
delegate void Demo(int n);
namespace MyDelegate
{
class TestDelegate
{
static int num = 10;
// Named methods
public static void DisplayAdd(int p)
{
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void DisplayMult(int q)
{
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int GetNum()
{
return num;
}
static void Main(string[] args)
{
// 1. ใช้ Anonymous Method
Demo dm = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
// เรียกใช้ anonymous method
dm(15); // แสดง: Anonymous Method: 15
// 2. ใช้ Named Method (DisplayAdd)
dm = new Demo(DisplayAdd);
dm(10); // แสดง: Named Method: 20
// 3. ใช้ Named Method อีกตัว (DisplayMult)
dm = new Demo(DisplayMult);
dm(4); // แสดง: Named Method: 80
Console.ReadKey();
}
}
}
ผลลัพธ์
Anonymous Method: 15
Named Method: 20
Named Method: 80
Anonymous Method vs Lambda Expression
ใน C# 3.0+ ควรใช้ Lambda Expression (=>) แทน เพราะกระชับและทันสมัยกว่า
| รูปแบบ | ตัวอย่าง |
|---|---|
| Anonymous Method (C# 2.0) | delegate(int x) { return x * 2; } |
| Lambda Expression (C# 3.0+) | x => x * 2 |
ตัวอย่างเทียบเท่า
// Anonymous Method
Func doubleAnon = delegate(int x) { return x * 2; };
// Lambda Expression (แนะนำ)
Func doubleLambda = x => x * 2;
// หลายพารามิเตอร์
Func addAnon = delegate(int a, int b) { return a + b; };
Func addLambda = (a, b) => a + b;
// ไม่มีพารามิเตอร์
Action sayHelloAnon = delegate() { Console.WriteLine("Hello"); };
Action sayHelloLambda = () => Console.WriteLine("Hello");
Closure (การจับตัวแปรภายนอก)
Anonymous Method และ Lambda สามารถเข้าถึงตัวแปรในขอบเขตภายนอกได้ (captured variables)
int factor = 10;
Func multiply = delegate(int x)
{
return x * factor; // จับตัวแปร factor
};
Console.WriteLine(multiply(5)); // 50
factor = 20;
Console.WriteLine(multiply(5)); // 100 (ใช้ค่าใหม่!)
ข้อดีและข้อจำกัด
ข้อดี
- ลดโค้ด boilerplate (ไม่ต้องสร้างเมธอดแยก)
- เหมาะสำหรับ callback, event handlers, LINQ
- รองรับ Closure
ข้อจำกัด
- ไม่สามารถใช้
ref/outparameters ได้ - ไม่สามารถใช้
unsafecode ได้ - Debugging ยากกว่า named methods (stack trace ไม่มีชื่อ)
- Lambda Expression ทดแทนได้ทุกกรณีและดีกว่า
สรุป
- Anonymous Method = เมธอดไร้ชื่อสำหรับ Delegate (C# 2.0)
- รูปแบบ:
delegate(parameters) { body } - ปัจจุบันแนะนำให้ใช้ Lambda Expression (=>) แทน
- รองรับ Closure (จับตัวแปรภายนอก)
- เหมาะสำหรับ callback สั้นๆ และ LINQ queries