delegate实例代码

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

namespace _11._1._3
{
    class Program
    {
        delegate int MyDelegate(int p, int q);

        static void Main( )
        {
            MyDelegate arithMethod = null;
            string myOperate = null;

            Console.WriteLine("选择对3和4执行的算术操作:");
            Console.WriteLine("按“+”键执行加法操作;");
            Console.WriteLine("按“-”键执行减法操作;");
            Console.WriteLine("按“m”键求两个数的最大值。");
            char choice = (char) Console.Read( );

            switch(choice)
            {
                case '+':
                    arithMethod = new MyDelegate(Add);
                    myOperate = "加法";
                    break;
                case '-':
                    arithMethod = new MyDelegate(Subtract);
                    myOperate = "减法";
                    break;
                case 'm':
                    arithMethod = new MyDelegate(Max);
                    myOperate = "求最大值";
                    break;
                default :
                    arithMethod = new MyDelegate(Add);
                    myOperate = "加法";
                    break;
            }

            int r = arithMethod(3, 4);
            Console.WriteLine("\n对3和4执行{0}操作后的结果是:{1} ",myOperate, r);

            Console.ReadLine();
            Console.ReadLine();

        }

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

        static int Subtract(int a, int b)
        {
           return a - b;
        }

        static int Max(int a, int b)
        {
            if(a > b)
            {
               return a;
            }
            else
            {
               return b;
            }
        }
    }
}

 

转载于:https://my.oschina.net/zhangqiliang/blog/1925765

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值