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

Generic Delegates ใน C# (Delegate แบบ Generic)

Generic Delegates ไม่ต้อง Define Delegate Statement เอง อยู่ใน Namespace System

กำหนด Generic Delegate ด้วย Type Parameters:

delegate T myDelegate<T>(T n);

ตัวอย่าง

using System;
using System.Collections.Generic;

delegate T myDelegate<T>(T n);

namespace GenericDelegateAppl
{
    class TestDelegate
    {
        static int num = 5;
        public static int AddNum(int p) { num += p; return num; }
        public static int MultNum(int q) { num *= q; return num; }
        public static int getNum() { return num; }

        static void Main(string[] args)
        {
            myDelegate<int> nc1 = new myDelegate<int>(AddNum);
            myDelegate<int> nc2 = new myDelegate<int>(MultNum);
            nc1(50); Console.WriteLine("Value of Num: {0}", getNum()); // 55
            nc2(10); Console.WriteLine("Value of Num: {0}", getNum()); // 550
            Console.ReadKey();
        }
    }
}