C#匿名方法

在这里插入图片描述


阅读时间:4min

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

  • 命名方法:指定方法名,可被实例化(new 对象),可被赋值。
	//声明一个委托
  	 delegate int del(int val);
  	//有一个proj对象,写一个满足委托结构的处理方法
  	 int func(int a)
  	{
  		return a;
  	}
  	//指定委托
  	del d=proj.func;
  • 匿名方法:不单独再类中写满足委托格式的处理方法,而是直接将处理用的参数及代码块直接订阅给委托。
    例:
	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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值