C# 委托 delegate Action Func

个人理解
就是说我现在有一个方法需要实现 但是我还没有想好 可是我知道我需要输入的参数和输出的类型
那么我就可以使用委托的方式先写在这里后面在补上
三种方式
1、delegate
2、Action
3、Func

First:
delegate 需要提前声明

 delegate void Something(int a);

我知道一个函数输入一个int类型的参数无返回类型
我可以在主函数之前delegate定义好后 在主函数中使用

Something a = new Something(getnum);

getnum这个参数必须要是一个static类型无返回且参数为int类型的函数名
而且不需要立马声明只需要后续声明好了就可以或者使用其他类型同条件的函数代替

Second:
Action是不需要提前定义的 节省了提前定义的步骤 简洁主要用这个
但是只能用于委托无返回参数的函数
可直接在主函数中写

Action<T,T> 函数名 = new Action<T,T>(委托的函数);
函数类型有几个写几个

third:
Func<T,T,T,out TResult>
使用方式一样只不过最后一个参数是返回值:
简单使用看下面代码

        delegate void Something(int a);

        static void Main(string[] args)
        {
            Something a = new Something(getnum);
            Action Nothing = new Action(nothing);
            Action<int> AddSelf = new Action<int>(addself);
            Action<int,int> AddNum = new Action<int,int>(addnum);
            Func<int, int, int> returnaddnumber = new Func<int, int, int>(return_addnum);
            a ();
            Nothing();
            AddSelf(5);
            AddNum(5, 6);
            int k = returnaddnumber(4, 9);
        }
        static void getnum(int a)
        {
            a += 1;
        }

        public static void nothing()
        {
        }
        public static void addself(int a)
        {
            a = a + a;
        }
        public static void addnum(int a, int b)
        {
            a = a + b;
        }

        public static int return_addnum(int a, int b)
        {
            return a + b;
        }
    }

还有一种就是把它当作函数指针来用

  static void Main(string[] args)
        {
          Action<int, int> addd = new Action<int, int>(add);
          Action<int, int> addd = new Action<int, int>(add);
          Calculate(add, 25, 10);
      	  Calculate(addd, 25, 10);
 
        }

        static void add(int a, int b)
        {
            int c= a + b;
        }       
        
        static void addd(int a, int b)
        {
            int c= a - b;
        }
        static void Calculate(Action<int, int> addd, int a, int b)
        {
            
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值