C#内置委托(Action)(Func)
概述
在 C# 中,委托是一种类型,它表示对具有特定参数列表和返回类型的方法的引用。C# 提供了一些内置委托,使得开发者可以更方便地使用委托功能,无需手动定义委托类型。本文将详细介绍 Action
和 Func
这两个常用的内置委托。
Action 委托
Action
委托用于表示没有返回值的方法。它可以有 0 到 16 个输入参数,这些参数的类型可以不同。
无参数的 Action 委
// 不支持返回值的内置委托
Action action = new Action(() =>
{
Console.WriteLine("无参数委托");
});
action();
在这个例子中,我们创建了一个无参数的 Action
委托 action
,并使用 Lambda 表达式为其赋值。当调用 action()
时,会执行 Lambda 表达式中的代码,输出 无参数委托
。
带参数的 Action 委托
// 带参数不可以有返回值
// 使用方法
Action<string, int> action1 = new Action<string, int>(MyAction);
// 使用匿名函数
Action<string, int> action2 = (a, b) => {
Console.WriteLine($"我叫{a},今年{b}岁");
};
action2("凡凡", 18);
static void MyAction(string a, int b)
{
Console.WriteLine($"{a},{b}");
}
这里创建了两个带参数的 Action
委托。action1
委托引用了 MyAction
方法,action2
委托使用了匿名函数。Action<string, int>
表示该委托接受一个 string
类型和一个 int
类型的参数,并且没有返回值。
Func 委托
Func
委托用于表示有返回值的方法。它至少有一个泛型参数,最后一个泛型参数表示返回值类型,前面的泛型参数表示输入参数类型。
无参数的 Func 委托
// 带返回类型的委托
Func<string> func1 = new Func<string>(MyFunc);
Console.WriteLine(func1());
Func<string> func2 = () => { return "哈哈"; };
Console.WriteLine(func2());
static string MyFunc()
{
return "嘿嘿";
}
Func<string>
表示该委托没有输入参数,返回值类型为 string
。func1
委托引用了 MyFunc
方法,func2
委托使用了匿名函数。
带参数的 Func 委托
// 设置了三个泛型参数类型,前两个代表参数,最后一个代表返回
Func<string, int, bool> func3 = new Func<string, int, bool>(MyFunc2);
Func<string, int, bool> func4 = (a, b) => { return int.Parse(a) == b; };
Console.WriteLine(func3("1", 2));
Console.WriteLine(func4("2", 2));
static bool MyFunc2(string a, int b)
{
return int.Parse(a) == b;
}
Func<string, int, bool>
表示该委托接受一个 string
类型和一个 int
类型的参数,返回值类型为 bool
。func3
委托引用了 MyFunc2
方法,func4
委托使用了匿名函数。
总结
Action
委托适用于不需要返回值的方法,而 Func
委托适用于需要返回值的方法。通过使用这些内置委托,可以减少手动定义委托类型的工作量,使代码更加简洁和易于维护。
namespace _2.内置委托
{
internal class Program
{
static void Main(string[] args)
{
//不支持返回值的内置委托
Action action = new Action(() =>
{
Console.WriteLine("无参数委托");
});
action();
//带参数不可以有返回值
Action<string, int> action1 = new Action<string, int>(MyAction);//使用方法
Action<string, int> action2 = (a, b) => {
Console.WriteLine($"我叫{a},今年{b}岁");
};//使用匿名函数
action2("凡凡", 18);
//带返回类型的委托
Func<string> func1 = new Func<string>(MyFunc);
Console.WriteLine(func1());
Func<string> func2 =() => { return "哈哈"; };
Console.WriteLine(func2());
//设置了三个泛型参数类型,前两个代表参数,最后一个代表返回
Func<string, int, bool> func3 =new Func<string, int, bool>(MyFunc2);
Func<string, int, bool> func4 = (a, b) => { return int.Parse(a) == b; };
Console.WriteLine(func3("1",2));
Console.WriteLine(func4("2",2));
}
static void MyAction(string a,int b)
{
Console.WriteLine($"{a},{b}");
}
static string MyFunc()
{
return "嘿嘿";
}
static bool MyFunc2(string a,int b)
{
return int.Parse(a) == b;
}
}
}