delegate、Action、Func的用法

委托的特点

  1. 委托类似于 C++ 函数指针,但它们是类型安全的。
  2. 委托允许将方法作为参数进行传递。
  3. 委托可用于定义回调方法。
  4. 委托可以链接在一起。

delegate的用法

delegate void BookDelegate(string a,string b);
public MainWindow()
{
    InitializeComponent();
    BookDelegate method = new BookDelegate(Book);
    method("Hello", "World");
}
public void Book(string a, string b)
{

}

 Action的用法

Action<string, string> BookAction = new Action<string, string>(Book);
public MainWindow()
{
    InitializeComponent();
    BookAction("Hello", "World");
}
public static void Book(string a, string b)
{

}

 Func的用法

Func<string, string, string> FuncBook = new Func<string, string, string>(Book);
public MainWindow()
{
    InitializeComponent();
    Book("Hello", "World");
}
public static string Book(string a, string b)
{
    return String.Format("{0}{1}", a, b);
}

总结

  1. Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型
  2. Func可以接受0个至16个传入参数,必须具有返回值
  3. Action可以接受0个至16个传入参数,无返回值
原文地址:https://www.cnblogs.com/sntetwt/p/11170938.html