Csharp 简明教程

C

我们之前讨论过委托用于引用具有与委托相同的签名的任何方法。换言之,你可以使用该委托对象调用可由委托引用的方法。

We discussed that delegates are used to reference any methods that has the same signature as that of the delegate. In other words, you can call a method that can be referenced by a delegate using that delegate object.

Anonymous methods 提供了一种将代码块作为委托参数传递的技术。匿名方法是没有名称的方法,只有函数体。

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body.

你不需要在匿名方法中指定返回类型;该类型可从该方法函数体内推断出来。

You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.

Writing an Anonymous Method

匿名方法使用 delegate 关键字声明委托实例时进行声明。例如,

Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword. For example,

delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x) {
   Console.WriteLine("Anonymous Method: {0}", x);
};

代码块 Console.WriteLine("Anonymous Method: {0}", x); 是匿名方法的函数体。

The code block Console.WriteLine("Anonymous Method: {0}", x); is the body of the anonymous method.

该委托可以以同样的方式同时使用匿名方法和已命名的方法进行调用,即,通过将方法参数传递给委托对象。

The delegate could be called both with anonymous methods as well as named methods in the same way, i.e., by passing the method parameters to the delegate object.

例如,

For example,

nc(10);

Example

以下示例演示了此概念 −

The following example demonstrates the concept −

using System;

delegate void NumberChanger(int n);
namespace DelegateAppl {
   class TestDelegate {
      static int num = 10;

      public static void AddNum(int p) {
         num += p;
         Console.WriteLine("Named Method: {0}", num);
      }
      public static void MultNum(int q) {
         num *= q;
         Console.WriteLine("Named Method: {0}", num);
      }
      public static int getNum() {
         return num;
      }
      static void Main(string[] args) {
         //create delegate instances using anonymous method
         NumberChanger nc = delegate(int x) {
            Console.WriteLine("Anonymous Method: {0}", x);
         };

         //calling the delegate using the anonymous method
         nc(10);

         //instantiating the delegate using the named methods
         nc =  new NumberChanger(AddNum);

         //calling the delegate using the named methods
         nc(5);

         //instantiating the delegate using another named methods
         nc =  new NumberChanger(MultNum);

         //calling the delegate using the named methods
         nc(2);
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Anonymous Method: 10
Named Method: 15
Named Method: 30