Action
- 是系统内置(预定义)的一个委托类型
public delegate void Action();
- 可指向一个没有返回值且没有参数的方法
static void Main(string[] args)
{
Action test = myFun;
test ();
}
public static void myFun()
{
Console.WriteLine("Action test1");
}
Action<>
- 可添加参数
- 不能有返回值
static void Main(string[] args)
{
Action<string,string> a = fun;
a("par1"," par2");
}
public static void fun(string str1,string str2)
{
Console.WriteLine(str1 + str2);
}
Func<>
-
只能引用具有返回值的方法
当<>中只有一种类型时,为其指向函数的返回值类型
-
指定多种类型时,最后一个类型表示返回值类型,前面的表示所引用方法的参数列表的类型。
static void Main(string[] args)
{
Func<int, double> fun= test;
Console.WriteLine(fun(5));
}
public static double test(int num)
{
//求一个整数的阶乘
int res = 1;
for(int i=2;i<=num;i++)
{
res *= i;
}
return res;
}
// 120
示例2:异步调用获取返回值结果
//Func 只能用来引用具有返回值的方法,只有一种类型时:表示引用具有返回值但没有参数的方法
Func<int> func = this.RemoteService;
int iResult2 = func.Invoke();
//获取异步调用返回的结果
IAsyncResult asy2 = func.BeginInvoke(null,null);
int iResult3 = func.EndInvoke(asy2);