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.uj5u.com/net/17080.html
標籤:C#
