类文件中:
public class greeting { public void sayhiEnglish(string name) { Console.WriteLine("hello world,{0}",name); } public void sayhiChinese(string name) { Console.WriteLine("good morning,{0}", name); } public void sayhiAmerican(string name) { Console.WriteLine("merry christmas,{0}", name); } public void sayhiET(string name, peopletype type) { Console.WriteLine("%$^&**,{0}", name); } public void sayhidelegate(string name,Action<string> act) { Console.WriteLine("*********"); act.Invoke(name); Console.WriteLine("结束时间"+DateTime.Now+""); } }
program.cs文件中:
greeting g = new greeting(); Action<string> act = g.sayhiAmerican; g.sayhidelegate("1998",act); g.sayhidelegate("小明",new Action<string>(g.sayhiChinese));
一般委托的使用:委托使用必须保证参数和返回值相同
public delegate string fly(int a); static void Main(string[] args) { fly f = new fly(gh); Console.WriteLine(f(10)); } public static string gh(int s) { return (s + 10).ToString(); }