C#基础学习之【6】委托的使用

using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
   
    public class ImplementingClass
    {
        // 2. 定义用于委托调用的方法,它的返回值和参数列表必须与委托一致
        public int WhichIsBig(int a, int b)
        {
            if (a > b)
                return a;
            else
                return b;
        }

        public int WhichIsSmall(int a, int b)
        {
            if (a < b)
                return a;
            else
                return b;
        }
    }

    class Program
    {
        // 1. 用delegate关键字声明一个委托,定义它的返回值和参数列表(方法签名)
        public delegate int CallDelegate(int a, int b);

        // 在函数内使用委托
        public static int Process(int a, int b, CallDelegate call)
        {
            return call(a, b);
        }

        static void Main(string[] args)
        {
            // 3. 在程序中创建委托实例与步骤2创建的方法相关联
            CallDelegate delegateBig = new CallDelegate(new ImplementingClass().WhichIsBig);

            // 4. 用委托调用相关联的方法,执行ImplementingClass WhichIsBig
            int big = delegateBig(10, 20);

            // 另一种使用委托的方式, 执行ImplementingClass WhichIsSmall
            int small = Process(10, 20, new CallDelegate(new ImplementingClass().WhichIsSmall));

            // 输出
            Console.WriteLine(big);     // 输出最大值20
            Console.WriteLine(small);   // 输出最小值10

            // 输入任意键退出
            Console.ReadKey();
        }
    }
}


2、泛型委托

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    
    public class ImplementingClass
    {
        // 定义委托调用的方法
        public float WhichIsBig(int a, float b)
        {
            if (a > b)
                return a;
            else
                return b;
        }
    }

    class Program
    {
        // 定义一个泛型委托,它的参数可以是任意类型
        public delegate float CallDelegate<T, S>(T t, S s);

        static void Main(string[] args)
        {
            //实例化委托
            CallDelegate<int, float> delegateBig = new CallDelegate<int, float>(new ImplementingClass().WhichIsBig);

            //调用委托方法,执行ImplementingClass WhichIsBig
            float big = delegateBig(10, 20.5f);

            // 输出最大值20.5
            Console.WriteLine(big);

            // 输入任意键退出
            Console.ReadKey();
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值