c#1核心基础之委托
委托大概就是将一个行为用某种方式包含在一个对象中。
委托的构成:
1:声明委托类型
2:一个包含了要执行代码的方法
3:必须创建一个委托实例
4:调用委托实例
一个委托实例:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 委托 8 { 9 delegate void StringPressor(string input);//声明委托类型 10 11 class Person 12 { 13 static string name; 14 public Person(string name1) { name = name1; } 15 public static void Say(string message) { Console.WriteLine("{0} say :{1}", name, message); }//声明静态方法 16 17 } 18 class Background 19 { 20 public void Say(string message) { Console.WriteLine("{0}", message); }//声明实例方法 21 } 22 23 class Program 24 { 25 static void Main(string[] args) 26 { 27 Background Jon=new Background(); 28 Person Jerry=new Person("Jerry"); 29 //创建两个委托实例 30 StringPressor Tom,Jack; 31 Tom=new StringPressor(Person.Say); 32 Jack=new StringPressor(Jon.Say); 33 //调用委托 34 Tom("hello"); 35 Jack("你好"); 36 Console.Read(); 37 38 } 39 } 40 }

浙公网安备 33010602011771号