เมธอดนิรนามเป็นเมธอดที่ไม่มีชื่อ เมธอดเหล่านี้มีเทคนิคในการส่งผ่านบล็อคโค้ดเป็นพารามิเตอร์ของผู้รับมอบสิทธิ์
มีการประกาศเมธอดที่ไม่ระบุชื่อด้วยการสร้างอินสแตนซ์ของผู้รับมอบสิทธิ์ โดยมีคีย์เวิร์ดของผู้รับมอบสิทธิ์
ตัวอย่าง
using System;
delegate void Demo(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 50;
public static void AddNum(int p) {
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void MultNum(int q) {
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances using anonymous method
Demo d = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
d(100);
//instantiating the delegate using the named methods
d = new Demo(AddNum);
//calling the delegate using the named methods
d(5);
//instantiating the delegate using another named methods
d = new Demo(MultNum);
//calling the delegate using the named methods
d(2);
Console.ReadKey();
}
}
} ผลลัพธ์
Anonymous Method: 100 Named Method: 55 Named Method: 110
ข้างบนนี้เป็นวิธีนิรนามของเรา
Demo d = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};