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

Action Delegate ใน C#

Action เป็น Delegate แบบ Generic ที่อ้างอิงเมธอดที่มีประเภทคืนค่าเป็น void สามารถรับพารามิเตอร์ได้ 0 ถึง 16 ตัว

การประกาศและใช้งาน

Action del = Display; // อ้างอิงเมธอด Display ที่รับ int
del(2); // เรียกผ่าน Delegate

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

using System;

public class Demo
{
    public static void Main()
    {
        Action del = Display;
        del(2); // แสดงผล 2
    }

    public static void Display(int val)
    {
        Console.WriteLine(val);
    }
}

ผลลัพธ์

2

ประเภท Action ที่พบบ่อย:

  • Action - ไม่มีพารามิเตอร์
  • Action<T> - 1 พารามิเตอร์
  • Action<T1, T2> - 2 พารามิเตอร์ ... จนถึง 16 พารามิเตอร์
ต่างจาก Func: Func ต้องมีคืนค่า (Return Type) ส่วน Action ไม่มีคืนค่า