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

Generic Delegates ใน C# คืออะไร

Generic Delegates คือ Delegate ที่ใช้ Type Parameter ทำให้ไม่ต้องประกาศ Delegate ใหม่ทุกครั้ง 定義在 System Namespace

Built-in Generic Delegates (Framework 3.5+)

DelegateSignatureคำอธิบาย
Func<T, TResult>TResult Method(T arg)มี Return Value (ได้ถึง 16 พารามิเตอร์)
Action<T>void Method(T arg)ไม่มี Return Value (ได้ถึง 16 พารามิเตอร์)
Predicate<T>bool Method(T arg)คืนค่า Boolean (สำหรับ Filter/ شرط)

ตัวอย่าง: ใช้ Func และ Action

using System;

class Program
{
    static void Main()
    {
        // Func - รับ 2 int คืน int
        Func<int, int, int> add = (a, b) => a + b;
        Console.WriteLine("Add: " + add(5, 3)); // 8
        
        // Action - รับ string ไม่คืนค่า
        Action<string> print = s => Console.WriteLine("Msg: " + s);
        print("Hello");
        
        // Predicate - รับ int คืน bool
        Predicate<int> isEven = x => x % 2 == 0;
        Console.WriteLine("Is 4 Even? " + isEven(4)); // True
    }
}

ตัวอย่าง Custom Generic Delegate

// ประกาศ Generic Delegate
delegate T MyDelegate<T>(T n);

class Demo
{
    static int num = 5;
    
    static int AddNum(int p) { num += p; return num; }
    static int MultNum(int q) { num *= q; return num; }
    
    static void Main()
    {
        MyDelegate<int> d1 = AddNum;
        MyDelegate<int> d2 = MultNum;
        
        Console.WriteLine(d1(10)); // 15
        Console.WriteLine(d2(2));  // 30
    }
}

ประโยชน์

  • ลดการประกาศ Delegate ซ้ำ
  • Type Safety ที่ Compile-time
  • ใช้กับ LINQ, Events, Callbacks ได้สะดวก