• 首页
  • 新手教程库
  • 在线工具
  • 视频教程
  • 代码片段库
  • 更多功能
    • 在线测验
    • 手机APP
Hostwinds建站首选4刀起支持Linux/Win(支付宝)
PacificRack $12/年起三网线路优化(可支付宝)
国外VPS哪个最好?
搬瓦工VPS-新增日本机房限量方案年付69
HostDare CN2 GIA线路4k无压力
美国和欧洲vps
  1. 首页
  2. 新手教程库
  3. Microsoft技术教程
  4. C# - 匿名方法
C# - 概述 C# - 概述 C# - 环境 C# - 程序结构 C# - 基本语法 C# - 数据类型 C# - 类型转换 C# - 变量 C# - 常量和文字 C# - 运营商 C# - 决策 C# - 循环 C# - 封装 C# - 方法 C# - Nullables C# - 数组 C# - 字符串 C# - 结构 C# - 枚举 C# - 类 C# - 继承 C# - 多态性 C# - 运算符重载 C# - 接口 C# - 命名空间 C# - 预处理器指令 C# - 正则表达式 C# - 异常处理 C# - 文件I / O. C# - 属性 C# - 反思 C# - 属性 C# - 索引器 C# - 代表 C# - 活动 C# - 收藏 C# - 泛型 C# - 匿名方法 C# - 不安全代码 C# - 多线程 C# - 有用的资源
教 程 目 录
上一节
下一节  

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

匿名方法提供了一种将代码块传递为委托参数.匿名方法是没有名称的方法,只是正文.

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

编写匿名方法

通过创建委托实例声明匿名方法,使用委托关键字.例如,

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

代码块 Console.WriteLine("匿名方法:{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
上一节
下一节  

相关新手教程:

Powershell教程
VBA教程
高级Excel教程
MFC 教程
C#教程
vb.net教程
Microsoft Project教程
LinQ教程
IT屋 ©2016-2020 京ICP备14011762号 鄂公网安备42018502004713号 站点地图 站点标签 意见&反馈  SiteMap <免责申明> 本站内容来源互联网,如果侵犯您的权益请联系我们删除.
  • 首页
  • 教程
  • 工具
  • 视频
  • 代码
  • 联系站长