Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Anonymous Methods ใน C#

Anonymous Methods (เมธอดไร้ชื่อ) ใช้ส่งบล็อกโค้ดเป็นพารามิเตอร์ของ Delegate โดยไม่ต้องประกาศเมธอดแยก

รูปแบบการประกาศ

delegate void NumberChanger(int n);
// ...
NumberChanger nc = delegate(int x) {
    Console.WriteLine("Anonymous Method: {0}", x);
};

ตัวอย่างโค้ดเต็ม

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);
        }
        static void Main(string[] args) {
            // ใช้ Anonymous method
            NumberChanger nc = delegate(int x) {
                Console.WriteLine("Anonymous Method: {0}", x);
            };
            nc(10);  // เรียก anonymous
            // ใช้ Named method
            nc = new NumberChanger(AddNum);
            nc(5);   // เรียก AddNum
            nc = new NumberChanger(MultNum);
            nc(2);   // เรียก MultNum
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Anonymous Method: 10
Named Method: 15
Named Method: 30

หมายเหตุ: ใน C# 3.0+ ควรใช้ Lambda Expressions แทน (กระชับกว่า): nc = x => Console.WriteLine("Lambda: {0}", x);