在.NET Core中使用委托 Action 和 Func

文章介绍了C#中的Action和Func委托,分别用于无返回值和有返回值的方法调用,展示了如何将这些方法作为参数传递给其他函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 委托,我们可以将具有返回值的方法作为参数传递给其他方法,并在需要时进行调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oh-caiii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值