C#匿名方法

在 2.0 之前的 C# 版本中,声明委托的唯一方式是使用命名方法。 C# 2.0 引入匿名方法,在 C# 3.0 及更高版本中,Lambda 表达式取代匿名方法作为编写内联代码的首选方式。

1. 区分命名方法和匿名方法

  • 命名方法:指定方法名,可被实例化(new 对象),可被赋值。
    例。
//声明一个委托  
 delegate int del(int val);
//有一个proj对象,有满足委托结构的处理方法
 int func(int a)
{
	return a;
}
//指定委托,func就是命名方法,可被赋值
del d=proj.func; 
  
  • b. 匿名方法:不单独再类中写满足委托格式的处理方法,而是直接将处理用的参数及代码块直接订阅给委托。
    例:
using System;
namespace Liming
{
	//创建委托
	delegate void val(int num);
	class Program
	{
		static void Main(string[] args)
		{
			//匿名方法,处理方法再方法框中指定
			val a=delegate(int num)
			{
			System.Console.WriteLine(num);
			};
			a(5);
		}
	}
   }

2.由于使用匿名方法无需创建单独的方法,因此可减少对委托进行实例化的编码开销。

using System;
using System.Threading;
namespace Liming
{
	class Program
	{
		static void Main(string[] args)
		{
			//创建一个线程,设置其委托构造参数,而无需创建新的方法,thread(可以后了解),
			//thread构造函数参数为委托类型。
			Thread th=new Thread(
				delegate()
				{
				System.Console.WriteLine("a");
				System.Console.WriteLine("b");
				}
			);
			th.Start();
		}
	}
}

3.注意:

  • 匿名方法块内不能有goto,break,continue跳转语句。无法使用外部范围的in,ref或out参数。
  • 可使用外部变量,要求委托块可访问的外部变量
    using System;
    using System.Threading;
    namespace Liming
    {
        //创建委托
        delegate void val(int num);
        class Program
        {
            static void Main(string[] args)
            {
                int n=9;
    	//n即为外部变量
                val vv=delegate(int num)
                {
                    System.Console.WriteLine(num+n);
                };
                vv(10);
            }
        }
    }
    
    
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值