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

  !!!

相關文章
相關標籤/搜索