• 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("---------"); } } }

  • 相关阅读:
    使用VGG16完成猫狗分类
    11.绘制网络结构
    11.模型载入
    session与cookie的区别---
    zookeeper 笔记
    53. Maximum Subarray
    !!!!!122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    235. Lowest Common Ancestor of a Binary Search Tree
    128. Longest Consecutive Sequence
  • 原文地址:https://www.cnblogs.com/shinians/p/13915275.html
Copyright © 2020-2023  润新知