C# 委托的简单应用

delegate是委托的关键字
委托的声明指定了一个函数名,其中包含了一个返回类型和参数列表。
在定义了委托后,就可以声明该委托类型的变量。接着把这个变量初始化与委托相同建明的函数引用。之后,就可以使用委托变量调用这个函数了。就像该变量是一个函数一样
有了引用函数的变量后,还可以执行不能用的其他方式完成的操作

下面就举一个简单的例子,来看看C#是怎么操作的

 

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

namespace Proccess
{
    class Program
    {
        delegate int ProccessDelegate(int i,int j);

        static int GetNumberPlus(int i, int j)
        {
            return i + j;
        }
        static int GetNumberMinus(int i,int j)
        {
            return i - j;
        }
        static void Main(string[] args)
        {
            ProccessDelegate ProccessDelegate = null;
            Console.WriteLine("Please enter 2 numbers :");
            string str1 = Console.ReadLine();
            string str2 = Console.ReadLine();
            int i = Convert.ToInt32(str1);
            int j = Convert.ToInt32(str2);
            Console.WriteLine("Enter you want to do");
            string str = Console.ReadLine();
            if (str.ToLower().Equals("p"))
            {
                ProccessDelegate = new ProccessDelegate(GetNumberPlus);
            }
            else
            {
                ProccessDelegate = new ProccessDelegate(GetNumberMinus);
            }
            Console.WriteLine(ProccessDelegate(i,j));
            Console.ReadKey();
                
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值