.NET 2.0 引入了一个泛型委托类型Action<T>,返回类型是Void,不必从匿名方法返回任何数据
签名如下:
public delegate void Action<in T>(T obj);
示例代码
//有参数的匿名方法
Action<string> ac1 = delegate (string text)
{
Console.WriteLine("有参的匿名方法,入参的值:"+text);
};
//同步执行
ac1("ac1");
//无参数的匿名方法
Action ac2 = delegate()
{
Console.WriteLine("无参数的匿名方法");
};
//同步执行
ac2();
//使用Invoke调用匿名方法
Action ac3 = delegate ()
{
Console.WriteLine("使用Invoke调用匿名方法");
};
//同步执行
ac3.Invoke();
//无参时省略小括号
Action ac4 =delegate
{
Console.WriteLine("无参时省略小括号");
};
//同步执行
ac4.Invoke();
//使用Lambda表达式
Action ac5 =()=>
{
Console.WriteLine("使用Lambda表达式");
};
//同步执行,Invoke方法时无参的
ac5.Invoke();
//使用BeginInvoke调用匿名方法
Action<string> ac6 = delegate (string text)
{
Console.WriteLine("使用BeginInvoke调用匿名方法,入参的值:" + text);
};
//异步执行
ac6.BeginInvoke("ac6", null, null);
总结:
1、Action方法有同步执行(Invoke)和异步(BeginInvoke)执行两种方式,
2、当Action委托有入参书Invoke方法只接受入参对象,BeginInvoke可以接受回调函数对象
3、deledate方法如果无入参时,可以省略小括号
4、可以使用delegate方式或者lambda表达式两种方式将匿名方法赋值给Action