C#中的委托

C#中的委托类似于C或C++中的函数指针。使用委托使程序员可以将方法引用封装在委托对象内。然后可以将该委托对象传递给可调用所引用方法的代码,而不必在编译时知道将调用哪个方法。与C或C++中的函数指针不同,委托是面向对象、类型安全的,并且是安全的。
 
举例:
class Program { static void OtherClassMethod(){ Console.WriteLine("Delegate an other class's method"); } static void Main(string[] args) { var test = new TestDelegate(); test.delegateMethod = new TestDelegate.DelegateMethod(test.NonStaticMethod); test.delegateMethod += new TestDelegate.DelegateMethod(TestDelegate.StaticMethod); test.delegateMethod += Program.OtherClassMethod; test.RunDelegateMethods(); } } class TestDelegate { public delegate void DelegateMethod(); //声明了一个Delegate Type public DelegateMethod delegateMethod; //声明了一个Delegate对象 public static void StaticMethod() { Console.WriteLine("Delegate a static method"); } public void NonStaticMethod() { Console.WriteLine("Delegate a non-static method"); } public void RunDelegateMethods() { if(delegateMethod != null){ Console.WriteLine("---------"); delegateMethod.Invoke();
Console.WriteLine("---------"); } } }

posted on 2020-11-02 16:56  徐大大大  阅读(133)  评论(0编辑  收藏  举报

导航