日期:2014-05-17  浏览次数:20893 次

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();
                
        }
    }
}

?