C# 中常用内置委托
Action
,Func
,EventHandler
和EventHandler<TEventArgs>
介绍
Action Delegate
封装一个没有返回值的方法
public delegate void Action();
样例
public static void Main()
{
Action showMethod = DisplayToConsole;
showMethod();
Console.ReadKey();
}
static void DisplayToConsole()
{
Console.WriteLine("hello");
}
Action <T > Delegate
封装一个没有返回值有一个参数的方法
public delegate void Action<in T>(T obj);
样例
public static void Main()
{
Action<string> messageTarget = ShowMessage;
messageTarget("Hello, World!");
Console.ReadKey();
}
static void ShowMessage(string message)
{
Console.WriteLine(message);
}
其它 Action
委托
Action 最多可以支持16个参数,但所有方法均无返回值。
Func <TResult > Delegate
代表有一个 TResult
类型的返回值没有参数的方法
public delegate TResult Func<out TResult>();
样例
static void Main(string[] args)
{
Func<string> func = GetValue;