C#委托

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

  例如A要作买苹果,可是A不想本身去买,就叫B去买,code

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

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

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

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

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

二、代码方法

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();
        }        

 

大体就是这样,有不一样意见的或者有更好的,但愿在评论区留言!!!static

纯属自做,若有雷同,纯属巧合,禁止用做商业用途di

  !!!

相关文章
相关标签/搜索