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);
        }
    }
}

你可能感兴趣的:(C#匿名方法)