C#委托

1、首先委托,就是和现实生活中的委托别人办事一样!

  例如A要做买苹果,但是A不想自己去买,就叫B去买,

  这个B就是委托(这里好像骂街了!别在意),B去买之前就肯定要就要知道A要买什么样的苹果,买多少之类的信息。

  A就说:“我一个一个和你说太麻烦了,你拿这个清单去照着买就行了”,然后B就拿这清单去了水果店。

  B跟水果店老板说:“啥也别问,照着清单上做进行,不要在这跟我逼逼赖赖的”

  水果店老板也就只有照着清单上写的做了。(这里的水果店老板就是执行者,执行了苹果这事)

这一套流程下来就是委托,而且是无返回的类型,水果店把苹果B,B把苹果交给交给A后,这就是有反回的类型

2、代码

static FileStream fs;
        static StreamWriter sw;
        // 委托声明
        public delegate void printString(string s);//我是委托清单字符串的委托都可以写

        // 该方法打印到控制台
        public static void WriteToScreen(string str)//我是执行者1
        {
            Console.WriteLine("The String is: {0}", str);
        }
        // 该方法打印到文件
        public static void WriteToFile(string s)//我是执行者2
        {
            fs = new FileStream(@"C:message.txt", FileMode.Append, FileAccess.Write);
            sw = new StreamWriter(fs);
            sw.WriteLine(s);
            sw.Flush(); 
            sw.Close();
            fs.Close();
      }
      // 该方法把委托作为参数,并使用它调用方法
      public static void sendString(printString ps)//PS是委托清单
      {

        //我是委托人
        //我按照清单委托printString去帮我做这件事
        ps("Hello World");
      }

         static void Main(string[] args)
        {

            printString ps1 = new printString(WriteToScreen);//生成委托清单
            printString ps2 = new printString(WriteToFile);//生成委托清单
            sendString(ps1);//把清单交给委托人
            sendString(ps2);
            Console.ReadKey();
        }        

大致就是这样,有不同意见的或者有更好的,希望在评论区留言!!!

纯属自作,如有雷同,纯属巧合,禁止用作商业用途

  !!!

原文地址:https://www.cnblogs.com/chenxiaojie/p/13156429.html