C#中的Action和Func(范型委托)

以前使用委托需要定义委托然后绑定方法,不够简洁。

现在通过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;
        }
    }
}

运行结果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值