zoukankan      html  css  js  c++  java
  • 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("---------"); } } }

  • 相关阅读:
    C++之queue模板类
    Longest Valid Parentheses
    Longest Substring Without Repeating Characters
    Subsets,Subsets II
    Unique Paths
    Letter Combinations of a Phone Number
    Restore IP Addresses
    [string]Roman to Integer,Integer to Roman
    [string]Reverse Words in a String
    [string]Regular Expression Matching
  • 原文地址:https://www.cnblogs.com/shinians/p/13915275.html
Copyright © 2011-2022 走看看