1.我们来看一下 Action 委托。Action 委托表示一个没有返回值的方法,它可以接受零到多个参数。下面是一个使用 Action 委托的示例:
public class Calculator
{
public static void Add(int a, int b)
{
int sum = a + b;
Console.WriteLine($"The sum of {a} and {b} is {sum}.");
}
}
class Program
{
static void Main(string[] args)
{
// 使用 Action 委托调用 Calculator 类的 Add 方法
Action<int, int> addAction = Calculator.Add;
addAction(3, 5);
}
输出结果为:
The sum of 3 and 5 is 8.
2.通过使用 Action 委托,我们可以将方法作为参数传递给其他方法,并在需要时进行调用。
委托Func表示一个有返回值的方法,并且可以接受0到16个参数。
接下来,我们来看一下 Func 委托。Func 委托表示一个具有返回值的方法,它可以接受零到多个参数。Func 委托的最后一个泛型参数表示方法的返回类型。下面是一个使用 Func 委托的示例:
public class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
// 使用 Func 委托调用 Calculator 类的 Add 方法
Func<int, int, int> addFunc = Calculator.Add;
int sum = addFunc(3, 5);
Console.WriteLine($"The sum of 3 and 5 is {sum}.");
}
}
输出结果为:
The sum of 3 and 5 is 8.
通过使用 Func 委托,我们可以将具有返回值的方法作为参数传递给其他方法,并在需要时进行调用。