| 一、委托是啥? 
 委托是一个类,定义方法的类型,将方法作为另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以有效的避免在程序中使用大量的if-else/switch语句,同时也使程序具有更好的可扩展性。
 简单点说就是将方法作为另一个方法的参数
 
 二、如何使用委托?
 
 1.定义委托
 [访问修饰符] delegate 返回类型 委托名称(形参)
 public delegate void MyDelegate(string name);
 因为Delegate是一个类,所以在任何可以声明类的地方都可以声明委托,可以定义在类的外面,也可以定义在类的里面。
 注意:委托和方法名必须具有相同的参数和返回值
 2.声明委托
 [访问修饰符] 委托名 委托实例化名;
 MyDelegate  myDelegate;
 3.创建委托对象
 委托实例化名 = new 委托名(某类方法)
 注意:当实例化委托时,要提供一个引用方法,将其作为构造方法的参数,被引用的这个方法必须对委托有相同的参数(即签名)。
 第一种写法
 MyDelegate myDelegate=new MyDelegate(example.Method);
 MyDelegate myDelegate1=new MyDelegate(new Example().Method);
 第二种写法
 MyDelegate myDelegate2 = example.Method;
 MyDelegate myDelegate3 = new Example().Method;
 暂时学这二种,还有几种写法,慢慢学。
 
 4.委托使用
 委托实例化名(实参)
 myDelegate("Hello World");
 
 [C#] 纯文本查看 复制代码     class Program
    {
        delegate void MyDelegate(string message);
        public class Example
        {
            public void Method(string message){
                Console.WriteLine(message);
            }
        }
        static void Main(string[] args)
        {
            Example example = new Example();
            MyDelegate myDelegate = new MyDelegate(example.Method);
            MyDelegate myDelegate1 = new MyDelegate(new  Example().Method);
            MyDelegate myDelegate2 = example.Method;
            MyDelegate myDelegate3 = new Example().Method;
            myDelegate("Hello World");
            Console.ReadKey();
        }
    }5.带返回值委托
 当创建委托对象时,委托的返回值必须和委托的方法相对应。
 
 [C#] 纯文本查看 复制代码     class Program
    {
        delegate string MyDelegate(string message);
        public class Example
        {
            public string Method(string message)
            {
                return "Hello" + message;
            }
        }
        static void Main(string[] args)
        {
            Example example = new Example();
            MyDelegate myDelegate = new MyDelegate(example.Method);
            MyDelegate myDelegate1 = new MyDelegate(new  Example().Method);
            MyDelegate myDelegate2 = example.Method;
            MyDelegate myDelegate3 = new Example().Method;
            myDelegate("World");
            Console.ReadKey();
        }
    }
 
 
 
 
 
 |