亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C# - 匿名方法

我们讨论了委托用于引用与委托具有相同签名的任何方法。换句话说,您可以使用该委托对象调用可由委托引用的方法。

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

您无需在匿名方法中指定返回类型;它是从方法体内的return语句推断出来的。

编写匿名方法

匿名方法是在创建委托实例时声明的,带有 delegate 关键词。例如,

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

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

可以使用匿名方法和命名方法以相同的方式调用委托,即将方法参数传递给委托对象。

例如,

nc(10);

示例

下面的例子演示了这个概念 -

现场演示
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();
      }
   }
}

当上面的代码编译并执行时,它会产生以下结果 -

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

C语言

  1. C#抽象类和方法
  2. C# 部分类和部分方法
  3. C# 密封类和方法
  4. C# 方法重载
  5. Python 匿名/Lambda 函数
  6. Java 匿名类
  7. Java 8 - 默认方法
  8. C# - 方法
  9. C# - 代表
  10. 什么是 EPA 方法 21?
  11. 加工中获得工件精度的常用方法(二)
  12. 4 局部电镀常用工艺方法