C#常用委托 Actin Func

1. Action Func

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 委托
{
    //此处介绍了Csharp中最常用的两个委托 Action 和 Func
    class Program
    {
        //delegate  委托 C 中使用指针代替直接调用
        //委托是指针的升级版本
        //函数指针  直接调用与 间接调用的结果是一致的
        static void Main(string[] args)
        {

            Caculator caculator = new Caculator();
            Action action = new Action(caculator.Report); //此处只需要方法名 不要加圆括号 这里不是调用
            //此时 已经使用了 Action 指向了 Report 这个方法
            caculator.Report();//此处为直接调用

            action.Invoke();   //此处为间接调用 与直接调用效果是一样的
            action();

            //使用Function 委托
            Func<int, int, int> func1 = new Func<int, int, int>(caculator.Add);  //委托的目标 输入两个int 返回的值为int
            Func<int, int, int> func2 = new Func<int, int, int>(caculator.Sub);
            int x = 100;
            int y = 200;
            int z = 0;
            int o = 0;
            z = func1.Invoke(x,y);    //委托 使用了间接调用
            o = func2(x, y);
            Console.WriteLine("z的结果数值是:"+z);
            Console.WriteLine("o的结果数值是:"+ o);




            Console.Read();
        }
    }

    class Caculator
    {
        public void Report()
        {
            Console.WriteLine("I have 3 methods");
        }

        public int Add(int a, int b)
        {
            int result = a + b;
            return result;
        }

        public int Sub(int a, int b)
        {
            int result = a - b;
            return result;
        }
    }
}

//一切皆地址

//直接调用 通过函数名直接获得函数所在的地址并且开始执行 
//间接调用 函数指针 cpu 找到存储的地址开始执行

//委托是函数指针的升级版

2. 自定义委托(委托的声明)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值