zoukankan      html  css  js  c++  java
  • 理解C#中的委托[翻译]

     

    委托的定义:
    委托是一种在对象里保存方法引用的类型,同时也是一种类型安全的函数指针。
    委托的优点:
    压缩方法的调用。
    合理有效地使用委托能提升应用程序的性能。
    用于调用匿名方法。
    委托的声明:
    委托应使用public delegate type_of_delegate delegate_name()的形式来声明。
    示例:public delegate int mydelegate(int delvar1,int delvar2)
    注意点:可以在不带参数或参数列表的情况下声明委托。
           应当遵循和声明方法一样的语法来声明委托。
    使用委托的示例程序:
    public delegate double Delegate_Prod(int a,int b);
    class Class1
     {
    static double fn_Prodvalues(int val1,int val2)
             {
              return val1*val2;
              }
    static void Main(string[] args)
     {   
                   //Creating the Delegate Instance
                   Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
                  Console.Write("Please Enter Values");
                  int v1 = Int32.Parse(Console.ReadLine());
                   int v2 = Int32.Parse(Console.ReadLine());
                   //use a delegate for processing
                   double res = delObj(v1,v2);
                   Console.WriteLine ("Result :"+res);
                   Console.ReadLine();
    }
     }
    示例程序解析:
    上面我用一段小程序示范了委托的使用。委托Delegate_Prod声明时指定了两个只接受整型变量的返回类型。同样类中名为fn_Prodvalues的方法也是如此,委托和方法具有相同的签名和参数类型。
    在Main方法中创建一个委托实例并用如下方式将函数名称传递给该委托实例:
    Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
    这样我们就接受了来自用户的两个值并将其传递给委托:
    delObj(v1,v2);
    在此委托对象压缩了方法的功能并返回我们在方法中指定的结果。
    多播委托:
    多播委托包含一个以上方法的引用。
    多播委托包含的方法必须返回void,否则会抛出run-time exception。
    使用多播委托的示例程序:
    delegate void Delegate_Multicast(int x, int y);
    Class Class2
    {
    static void Method1(int x, int y) {
      Console.WriteLine("You r in Method 1");
    }
    static void Method2(int x, int y) {
      Console.WriteLine("You r in Method 2");
    }
    public static void Main()
    {
      Delegate_Multicast func = new Delegate_Multicast(Method1);
    func += new Delegate_Multicast(Method2);
          func(1,2);             // Method1 and Method2 are called
          func -= new Delegate_Multicast(Method1);
          func(2,3);             // Only Method2 is called
       }
    }    
    示例程序解析:
    大家可以看到上面的示例程序分别定义了名为method1 和 method2的两个接受整型参数、返回类型为void的方法。
    在Main函数里使用下面的声明创建委托对象:
    Delegate_Multicast func = new Delegate_Multicast(Method1);
    然后使用+= 来添加委托,使用-=来移除委托。
    总结:
    这篇小文章将帮助您更好地理解委托。
  • 相关阅读:
    进程状态
    VMware虚拟机的三种联网方法及原理
    关于C++迭代器失效
    头文件:limits.h、float.h
    正则表达式之一:元符号
    MYSQL之批量插入数据库
    PHP之如何判断数字(数字字符串不算)
    使用Process Monitor来得到程序运行参数
    Abusing the C preprocessor
    1+1还是1+1=2?
  • 原文地址:https://www.cnblogs.com/springxie/p/1356145.html
Copyright © 2011-2022 走看看