C# - 动作委托 Action 是在 System 命名空间中定义的委托类型。 Action 类型委托与 Func 委托相同,只是 Action 委托不返回值。 换句话说,Action 委托可以与具有 void 返回类型的方法一起使用。
Action 带一个参数的定义如下
csharp
public delegate void Action<in T>(T obj);例如,以下委托打印一个 int 值。
csharp
class Program
{
static void ConsolePrint(int i)
{
Console.WriteLine(i);
}
static void Main(string[] args)
{
Action<int> printActionDel = ConsolePrint;
printActionDel(10); // 输出10
}
}您可以使用 new 关键字或直接分配一个方法来初始化 Action 委托:
csharp
Action<int> printActionDel = ConsolePrint;
//Or
Action<int> printActionDel = new Action<int>(ConsolePrint);一个 Action 委托最多可以接受 16 个不同类型的输入参数。
匿名方法也可以分配给 Action 委托,例如:
csharp
class Program
{
static void Main(string[] args)
{
Action<int> printActionDel = delegate (int i)
{
Console.WriteLine(i);
};
printActionDel(10); // 输出 10
}
}Lambda 表达式也可以与 Action 委托一起使用:
csharp
class Program
{
static void Main(string[] args)
{
Action<int> printActionDel = (int i) =>
{
Console.WriteLine(i);
};
//可以简化成
Action<int> printActionDel2 = (int i) => Console.WriteLine(i);
printActionDel(10); // 输出 10
}
}因此,任何不带返回值的方法,都可以跟Action托托一起使用。
Action 当做参数
csharp
class Program
{
static void Main(string[] args)
{
Print(i => Console.WriteLine($"hello:{i}")); // 输出 hello:5
//直接在Print里面用lambda表达式定义了一个函数,
// 下面这些也是可以的。
Print(i => { Console.WriteLine($"hello:{i}"); });
Print((i) => { Console.WriteLine($"hello:{i}"); });
Print((int i) => { Console.WriteLine($"hello:{i}"); });
Action<int> action = (int i) =>
{
Console.WriteLine(i);
};
Print(action);
}
public static void Print(Action<int> action)
{
int i = 5;
action(i);
}
}Action 和 Func 委托的优点
- 轻松快速地定义委托。
- 使代码简短。
- 整个应用程序中的兼容类型。
要记住的要点:
- Action 委托与 Func 委托相同,只是它不返回任何内容。 返回类型必须为空。
- Action 委托可以有 0 到 16 个输入参数。
- Action 委托可以与匿名方法或 lambda 表达式一起使用。
