Action 和 Func都是C#系统中内置的委托类型。
Action
Action
Action<T>
Action<T1, T2>
Action<T1, ... T16>
这其中 T表示的是方法参数,Action中最多可有16个方法参数
Action
首先不带任何参数的,需要一个返回值为void类型,无参数的函数如下:
static void Main(string[] args)
{
Action act = PrintMethod1;
act();
Console.ReadKey();
}
static void PrintMethpriod1()
{
Console.WriteLine("PrintMethod1");
}
创建一个 Action 类型 act,然后将 PrintMethpriod1 赋值给act,这样当我们调用 act() 的时候,会执行 PrintMethpriod1 函数。
Action<T1, … T16>
当我们需要调用带参数的函数是,则需要 Action<T1, … T16>,如下列子:
static void Main(string[] args)
{
Action<int, string> act = PrintMethod1;
act(12, "sola = ");
Console.ReadKey();
}
static void PrintMethod1(int a, string str)
{
Console.WriteLine(str + a.ToString());
}
创建一个Action<int, string> act, 这个意思就是需要一个 两个参数的函数,第一个参数int型,第二个参数是string型。然后将符合条件的函数 PrintMethod1 赋值给act,当执行act(12, "sola = ");的时候,就会调用PrintMethod1函数,则输出为:sola = 12
当然,Action<T … T16> 还可以更多的参数,但最多只能够16个。
Func
当然,不带参数的和带参数的都已经有了,若带返回值的就需要 Func 内置委托了。
Func 这个是可以委托一个带返回值的函数。同样传递参数可以是0个,最多16个。
Func<out TResult>
Func<T, out TResult>
Func<T...T16, out TResult>
Func<out TResult>
首先来看不带参数切具有返回值的列子:
static string Test()
{
return "hahah";
}
static void Main(string[] args)
{
Func<string> func = Test;
string str = func();
Console.WriteLine(str);
Console.ReadKey();
}
首先,Func<string> func 这个意思就是定义一个返回值是string类型无参数的委托,所以我们可以将Test函数赋值给func,当我们要调用时 func() 需要用string类型来接受,所以输出的字符串即为 hahah
Func<T…T16, out TResult>
下面的列子就是带参数带返回值的委托;
static void Main(string[] args)
{
Func<int, int, string> str = Test;
string ret = Test(1, 2);
Console.WriteLine(ret);
Console.ReadKey();
}
static string Test(int a, int b)
{
return a.ToString() + " + " + b.ToString();
}
先看我们使用的func委托 Func<int, int, string> str, 这个的意思是定义一个返回值为string ,带两个参数,第一个为int型,第二个也是int型的委托 str
这里Func的最后一个参数类型就是表示的是委托函数的返回类型,其他的都是附带的参数类型。
将 符合条件的函数 Test赋值给str,让只能够Test(1,2)时候,则需要string类型接受,所以最终输出为 1 + 2
Func 和 Action区别
区别:Func必须是带返回值,Action 不能有返回值
相同:都是系统内置的委托,都可以带参数切参数最多为16个。