Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khởi tạo Delegate trong C#

Delegate: type-safe function pointer.

1. Khởi tạo từ method

public delegate void PrintString(string s);

PrintString ps1 = new PrintString(WriteToScreen);
// Hoặc ngắn gọn (method group conversion)
PrintString ps2 = WriteToScreen;

2. Anonymous method (C# 2.0)

delegate void Del(string str);
Del d = delegate(string name)
{
    Console.WriteLine("Notification: {0}", name);
};

3. Lambda expression (C# 3.0+) - Khuyến nghị

Del d = name => Console.WriteLine("Notification: {0}", name);

Ví dụ hoàn chỉnh

using System;

delegate int NumberChanger(int n);

namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 10;
        
        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)
        {
            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);
            
            nc1(25);
            Console.WriteLine("Num: {0}", GetNum()); // 35
            
            nc2(5);
            Console.WriteLine("Num: {0}", GetNum()); // 175
            
            Console.ReadKey();
        }
    }
}

Kết quả

Num: 35
Num: 175

Built-in delegates: Action (void), Func<TResult>, Func<T, TResult>, Predicate<T> (bool).