以前使用委托需要定义委托然后绑定方法,不够简洁。
现在通过Action和Func可以简化委托的使用。
Action<T1,T2,T3,T4,...>表示有n个参数(参数类型可以不同),但没有返回值的委托。
Func<T1,T2,T3,T4,...,TResult>表示有n个参数(参数类型可以不同)且有一个返回值的委托(返回值类型为TResult)。
参考资料:
https://www.cnblogs.com/LipeiNet/p/4694225.html
以下为本人调试时的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Action和Func_范型委托_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("==========Action==========");
//0个参数
Action action0 = new Action(MyAction);
action0();
//1个参数
Action<string> action1 = new Action<string>(MyAction);
action1("chenwei");
//2个参数
Action<string, int> action2 = new Action<string, int>(MyAction);
action2("chenwei", 500);
//3个参数
Action<string, int, bool> action3 = new Action<string, int, bool>(MyAction);
action3("chenwei", 500, true);
Console.WriteLine();
Console.WriteLine("==========Func==========");
//0个参数
Func<string> func0 = new Func<string>(MyFunc);
Console.WriteLine(func0());
//1个参数
Func<string, string> func1 = new Func<string, string>(MyFunc);
Console.WriteLine(func1("henry"));
//2个参数
Func<string, int, string> func2 = new Func<string, int, string>(MyFunc);
Console.WriteLine(func2("henry",100));
//3个参数
Func<string, int, bool, string> func3 = new Func<string, int, bool, string>(MyFunc);
Console.WriteLine(func3("henry",100,true));
Console.ReadLine();
}
static void MyAction()
{
Console.WriteLine("0个参数");
}
static void MyAction(string name)
{
Console.WriteLine(name);
}
static void MyAction(string name, int age)
{
Console.WriteLine(name + ":" + age);
}
static void MyAction(string name, int age, bool b)
{
Console.WriteLine(name + ":" + age + ":" + b);
}
static string MyFunc()
{
return "0个参数";
}
static string MyFunc(string name)
{
return "return:" + name;
}
static string MyFunc(string name, int age)
{
return "return:" + name + ":" + age;
}
static string MyFunc(string name, int age, bool b)
{
return "return:" + name + ":" + age + ":" + b;
}
}
}
运行结果: