什么是委托。
委托是一種數據類型。
委托的作用。
把變化的東西封裝起來。
委托是引用變量,聲明后不賦值為null 所以使用前校驗非空。
class Program { static void Main(string[] args) { //2、使用委托。 // 先new一個委托類型的對象,並傳遞方法進去。即md委托保存了M1方法。 MyDelegate md = new MyDelegate(M1); //調用md委托就是調用M1方法 md(); } static void M1() { Console.WriteLine("一個沒有參數沒有返回值的方法"); } } //1、定義委托類型 //定義一個委托類型,用來保存無參數,無返回值的方法。 public delegate void MyDelegate();
目前來看,委托沒啥毛用,直接調用M1不就得了?
下面程序的作用是,傳入一個字符串,把每個人名都加上*
class Program { static void Main(string[] args) { string[] name = new string[] { "Sam", "Jill", "Penny" }; MyClass mc = new MyClass(); mc.Change(name); for (int i = 0; i < name.Length; i++) { Console.WriteLine(name[i]); } } } public class MyClass { public void Change(string[] str) { for (int i = 0; i < str.Length; i++) { str[i] = "*" + str[i] + "*"; } } }
但是現在需求變了,把每個人名都換成大寫。 就需要改變代碼。
而代碼部分,只有str[i] = "*" + str[i] + "*"; 是變化的。
就可以把這段代碼封裝起來。
class Program { static void Main(string[] args) { string[] name = new string[] { "Sam", "Jill", "Penny" }; MyClass mc = new MyClass(); mc.Change(name,ChangeValue); for (int i = 0; i < name.Length; i++) { Console.WriteLine(name[i]); } } static string ChangeValue(string str) { return str.ToUpper(); } } public class MyClass { public void Change(string[] str,ChangeDelegate ChangeValue) { for (int i = 0; i < str.Length; i++) { str[i] = ChangeValue(str[i]); } } } public delegate string ChangeDelegate(string str);