1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace 委托学习 7 { 8 public delegate void DeleShow(); 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //DeleShow ds = Show2.ShowIn; 14 //Show1.ShowOut(ds); 15 DeleShow ds; 16 Console.WriteLine("你想做什么?\n1.打印字符\n2.打开记事本"); 17 string str=Console.ReadLine(); 18 switch (str) 19 { 20 //这里就好像是多态,但是这里是同一个方法(Show1.ShowOut())展现出不同方法体的特征, 21 //就像是多态的方法表现形式一样。 22 case "1": ds = Show2.ShowIn; break; 23 case "2": ds = Open.OpenNotepad; break; 24 default: ds = null; break; 25 } 26 Show1.ShowOut(ds); 27 Console.ReadKey(true); 28 } 29 } 30 class Show1 31 { 32 public static void ShowOut(DeleShow show) 33 { 34 //在ShowOut这个方法体里面调用在其它类下的其它方法。委托的一种实现。 35 Console.WriteLine("=================="); 36 37 //当show没有赋值的时候,或者赋值表达式不由你进行控制的时候,你是不知道show会执行什么的,那么这样就灵活多了。 38 //如果在这里直接写ShowIn方法,就写死了,灵活度就降低了。 39 show(); 40 Console.WriteLine("=================="); 41 } 42 } 43 class Show2 44 { 45 public static void ShowIn() 46 { 47 Console.WriteLine("欢迎来到黑马训练营"); 48 } 49 } 50 class Open 51 { 52 public static void OpenNotepad() 53 { 54 System.Diagnostics.Process.Start("notepad.exe"); 55 } 56 } 57 }
原文:http://www.cnblogs.com/dlwcg/p/3615035.html