C#中的Delegate机制(Delegate in C#)

来源:互联网 发布:cms源码 编辑:程序博客网 时间:2024/05/31 19:11

暑期闲来无事,翻了翻《C#入门经典》一书,对个人认为比较重要或者我们经常比较容易忽略或遗忘的东西,做了一些读书笔记。今天对其中的一些内容做一个简单的整理,一方面自己再加深一遍印象,同时,也希望对读者有所帮助。

今日关键词:Delegate

一、是什么?

Definition: A delegate is a type that enables you to store references to functions.
首先这句话告诉我们Delegate是指一种type,这种特殊的type能实现可以作为function的参数使用。可是Delegate作为参数有什么好处呢,我们带着疑问继续下面的学习。

备注:Functions in C# are a means of providing blocks of code that can be executed at any point in an application。


二、怎么用

Delegate的申明:

Delegates的申明和Function的申明相似,但Delegates没有方法体,通过delegate关键字进行申明。
申明格式:delegate [return type] [delegateName](type1 param1, type2 param2 ...)

   After defining a delegate, you can declare a variable with the type of that delegate. You can then initialize this variable as a reference to any function that has the same signature as that delegate. Once you have done this, you can call that function by using the delegate variable as if it were a function.
When you have a variable that refers to a function, you can also perform other operations that would be impossible by any other means. For example, you can pass a delegate variable to a function as a parameter, then that function can use the delegate to call whatever function it refers to, without having knowledge as to what function will be called until runtime.

 

看下面一个例子:

有两个数,现在需要完成这两个数的一种运算,可能是加减乘除,也可能是其他,然后返回计算结果。


        delegate double CalculateDelegate(double one, double another);
        static double Divide(double one, double another)        {            return one / another;        }        static double Add(double one, double another)        {            return one + another;        }
         
        static double ExcuteCalculate(CalculateDelegate c);
        
        public static void main(){
            CalculateDelegate cal = new CalculateDelegate(Divide)          
            //use the delegate variable like a function            double result0 = cal(2.1,3.14);          
            //use the delegate reference as a function parameter              double result = ExecuteCalculate(cal);            Console.WriteLine("=========================================");            Console.WriteLine("【第一种方式】2.1与3.14相除的结果是:{0}",result0);            Console.WriteLine("【第二种方式】2.1与3.14相除的结果是:{0}",result);            Console.WriteLine("=========================================");            Console.ReadKey()
}