C#基礎——委托
阿新 • • 發佈:2018-09-11
一個 args ole [] 類型 沒有 返回 理解 class
以下所寫是個人對委托的理解,為了加深對委托的理解和記憶,特地寫下來。
委托的介紹:
委托和事件是一對好搭檔,事件在之後的文章中做介紹。C#中常使用委托做回調。
委托其實是一個類,在編譯之後的編譯文件中可以看到,委托的類型是class。
1.聲明委托
使用關鍵字:delegate,
如下所示:這裏聲明了一個沒有返回值的委托。
public delegate void ConsloleWrite(string str);
2.使用委托
public class Program { static void Main(string[] args) { Console.Write("請輸入:"); string str = Console.ReadLine(); TestDelegate td = new TestDelegate(); td.DelegatePrint(Convert.ToInt32(str), print); } public static void print<T>(T str) { Console.WriteLine(str); Console.ReadKey(); } }public class TestDelegate { public void DelegatePrint<T>(T str,ConsloleWrite<T> write) { write(str); } public delegate void ConsloleWrite<in T>(T obj); }
C#基礎——委托