时间越长越感觉自己学习的只是还是太少啊~,最近看了Head First这本书(好书啊有木有),这本书里面有个装饰者模式,用到了委托...突然想起来~以前一直用过,但是具体为什么用也没仔细想过,以前看了很多 网上的学习资料说委托,MSDN上的专业资料可能写的很全但有的人会感觉太抽象。
所谓委托:delegate 是一种可用于封装命名或匿名方法的引用类型。委托类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。其实简单的说在我看来,委托现在给我带来的好处在运行期可以动态改变你要处理的东西,委托里面的参数其实传送的就是方法引用,把方法名当参数传,当然必须是保证返回值和方法签名是一样的~
下面是一部分简单的小例子,其实委托没我们想象的那么复杂
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DavidTest { public class Delegatebase { public delegate double CalculateMethod(double firstParam, double secondParam); /// <summary> /// Add Method /// </summary> /// <param name="first_param"></param> /// <param name="second_param"></param> /// <returns></returns> public static double Plus(double first_param, double second_param) { return first_param + second_param; } /// <summary> /// Minus Method /// </summary> /// <param name="first_param"></param> /// <param name="second_param"></param> /// <returns></returns> public static double Minus(double first_param, double second_param) { return first_param - second_param; } /// <summary> /// Mutiply Method /// </summary> /// <param name="first_param"></param> /// <param name="second_param"></param> /// <returns></returns> public static double Mutiply(double first_param, double second_param) { return first_param * second_param; } /// <summary> /// Divide Method /// </summary> /// <param name="first_param"></param> /// <param name="second_param"></param> /// <returns></returns> public static double Divide(double first_param, double second_param) { return second_param == 0 ? 0 : first_param / second_param; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DavidTest { class Program { static void Main(string[] args) { #region 委托测试 Delegatebase.CalculateMethod delegatePlus = new Delegatebase.CalculateMethod(Delegatebase.Plus); Delegatebase.CalculateMethod delegateMinus = new Delegatebase.CalculateMethod(Delegatebase.Minus); Delegatebase.CalculateMethod delegateMutiply = new Delegatebase.CalculateMethod(Delegatebase.Mutiply); Delegatebase.CalculateMethod delegateDivide = new Delegatebase.CalculateMethod(Delegatebase.Divide); Console.WriteLine("Plus Result: {0}", delegatePlus(1,2)); Console.WriteLine("Minus Result: {0}", delegateMinus(1, 2)); Console.WriteLine("Mutiply Result: {0}", delegateMutiply(1, 2)); Console.WriteLine("Divide Result: {0}", delegateDivide(1, 2)); #endregion Console.ReadLine(); } } }