วิธีการที่ไม่ระบุชื่อมีเทคนิคในการส่งบล็อกโค้ดเป็นพารามิเตอร์ผู้รับมอบสิทธิ์ เมธอดนิรนามเป็นวิธีที่ไม่มีชื่อ มีแต่เนื้อหา
ให้เราดูวิธีการประกาศวิธีการที่ไม่ระบุชื่อใน C# -
delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
}; ตัวอย่าง
ต่อไปนี้คือตัวอย่างการใช้เมธอด Anonymous ใน C#
using System;
delegate void NumberChanger(int n);
namespace DelegateAppl {
class Demo {
static int num = 10;
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
NumberChanger nc = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
nc(10);
//instantiating the delegate using the named methods
nc = new NumberChanger(AddNum);
//calling the delegate using the named methods
nc(5);
//instantiating the delegate using another named methods
nc = new NumberChanger(MultNum);
//calling the delegate using the named methods
nc(2);
Console.ReadKey();
}
}
} ผลลัพธ์
Anonymous Method: 10 Named Method: 15 Named Method: 30