Delegate là kiểu đại diện cho tham chiếu đến methods với parameter list và return type cụ thể. Khi instantiate delegate, có thể associate instance với method có signature và return type compatible. Có thể invoke method qua delegate instance.
Func Delegate
Func là generic delegate trong namespace System. Có zero hoặc nhiều input parameters và một out parameter. Parameter cuối được coi là out parameter. Delegate này trỏ đến method nhận tối đa 16 parameters và trả về giá trị.
Func delegate với hai input và một output:
FuncAppend;
Ví dụ
using System;
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Func func = Append;
string fullName = func("Michael", "Jackson");
Console.WriteLine(fullName);
Console.ReadLine();
}
static string Append(string firstName, string lastName)
{
return firstName + lastName;
}
}
}
Kết quả
MichaelJackson
Action Delegate
Action là delegate type trong namespace System. Giống Func delegate nhưng Action delegate không trả về giá trị. Có thể dùng với method có void return type. Chứa tối thiểu 1, tối đa 16 input parameters, không có output parameter.
Action delegate với hai input:
ActionPrint;
Ví dụ
using System;
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Action action = AppendPrint;
action("Michael", "Jackson");
Console.ReadLine();
}
static void AppendPrint(string firstName, string lastName)
{
string fullName = firstName + lastName;
Console.WriteLine(fullName);
}
}
}
Kết quả
MichaelJackson