先上书面解释----委托(delegate)是一种可以把引用存储为函数的类型。委托最重要的用途事件和事件处理;
我的理解---处理事件用的是方法,委托是对方法的一种总结,(就像在结构中使用函数对变量的来进行总结一样,因为变量太多了,使用函数总结一下)因为方法太多了,使用委托(或者引用存储为函数,当然不带函数体,更类似是一种字段)
在老外的书籍中他把委托也弄到函数中了可以说是对函数的一种总结(国内翻译未详细解释因为在后面的事件中还会出现,所以这块有时候出现很迷惑,但他是对函数的总结,所以会在函数部分出现)
好吧上例子一个是结构体 一个是委托体 大家自己琢磨吧,如果方法多的话,委托体就有优势了
结构体
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DelegateAndStruct { class Program { // double ProcessDelegate(double param1, double param2); struct ProcessDelegate { public double Multiply( double param1,double param2) { return param1 * param2; } public double Divide(double param1, double param2) { return param1 / param2; } } static void Main(string[] args) { ProcessDelegate process; Console.WriteLine("Enter 2 numbers separated with a comma:"); string input = Console.ReadLine(); int commaPos = input.IndexOf(','); double param1 = Convert.ToDouble(input.Substring(0, commaPos)); double param2 = Convert.ToDouble(input.Substring(commaPos + 1, input.Length - commaPos - 1)); Console.WriteLine("Enter M to multiply or D to divide:"); input = Console.ReadLine(); double result; if (input == "M") //process = new ProcessDelegate(Multiply); result = process.Multiply(param1, param2); else // process = new ProcessDelegate(Divide); result = process.Divide(param1, param2); Console.WriteLine("Result: {0}",result ); Console.ReadKey(); } } }
委托体
class Program { delegate double ProcessDelegate(double param1, double param2); static double Multiply(double param1, double param2) { return param1 * param2; } static double Divide(double param1, double param2) { return param1 / param2; } static void Main(string[] args) { ProcessDelegate process; Console.WriteLine("Enter 2 numbers separated with a comma:"); string input = Console.ReadLine(); int commaPos = input.IndexOf(','); double param1 = Convert.ToDouble(input.Substring(0, commaPos)); double param2 = Convert.ToDouble(input.Substring(commaPos + 1, input.Length - commaPos - 1)); Console.WriteLine("Enter M to multiply or D to divide:"); input = Console.ReadLine(); if (input == "M") process = new ProcessDelegate(Multiply); else process = new ProcessDelegate(Divide); Console.WriteLine("Result: {0}", process(param1, param2)); Console.ReadKey(); } }