C# 中,匿名方法(Anonymous Methods) 是一种没有名称的内联方法,通常用于简化委托(delegate)的使用。匿名方法主要用于事件处理、临时逻辑,或者只使用一次的简短方法。名方法是 C# 中一种强大的特性,可以内联定义没有名称的方法,特别适用于事件处理和简单的委托回调。它们可以捕获外部变量形成闭包。虽然 Lambda 表达式在现代 C# 开发中更常用,但理解匿名方法仍然很重要,因为它们是 Lambda 表达式的基础,并且在一些旧的代码库中仍然存在。本文主要介绍C# 匿名方法。

1、C# 匿名方法的声明

可以使用 lambda 表达式或匿名方法来创建匿名函数。 建议使用 lambda 表达式,因为它们提供了更简洁和富有表现力的方式来编写内联代码。 与匿名方法不同,某些类型的 lambda 表达式可以转换为表达式树类型。匿名方法定义语法如下,

1)使用delegate 关键字创建委托实例来声明

delegate void MyDelegate(string s);
...
MyDelegate m = delegate(string x)
{
    Console.WriteLine("匿名方法: {0}", x);
};

2)使用 lambda 表达式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace cjavapy
{
    delegate void MyDelegate(string s);
    class Program
    {
        static void Main(string[] args)
        {
            //Expression<del> myET = x => x * x;
            MyDelegate m =  x=>Console.WriteLine("匿名方法: {0}", x);
            Console.ReadKey();
        }
    }
}

2、匿名方法的使用

在 C# 1.0 中,通过使用在代码中其他位置定义的方法显式初始化委托来创建委托的实例。 C# 2.0 引入了匿名方法的概念,作为一种编写可在委托调用中执行的未命名内联语句块的方式。 C# 3.0 引入了 lambda 表达式,这种表达式与匿名方法的概念类似,但更具表现力并且更简练。 这两个功能统称为匿名函数。 通常,面向 .NET Framework 3.5 或更高版本的应用程序应使用 lambda 表达式。

例如,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace cjavapy
{
    class Test
    {
        delegate void MyDelegate(string s);
        static void MyMethod(string s)
        {
            Console.WriteLine(s);
        }
        static void Main(string[] args)
        {
            //原始委托语法
            //使用指定方法初始化。
            MyDelegate md1 = new MyDelegate(MyMethod);
            // c# 2.0:一个委托可以被初始化
            //内部代码,称为“匿名方法”。这
            //方法以字符串作为输入参数。
            MyDelegate md2 = delegate (string s) { Console.WriteLine(s); };
            // c# 3.0。委托可以被初始化
            //一个lambda表达式lambda也接受一个字符串
            //作为输入参数(x)。x的类型由编译器推断。
            MyDelegate md3 = (x) => { Console.WriteLine(x); };
            // 调用委托。
            md1("C#");
            md2("Java");
            md3("Python");
            Console.ReadKey();
        }
    }
}

相关文档:.NET(C#) 匿名类

3、与 Lambda 表达式的区别

匿名方法(Anonymous Methods)和Lambda 表达式(Lambda Expressions)都可以用于简洁地定义委托(Delegate)的实现。虽然它们非常相似,但在语法、功能和使用场景上仍有一些关键区别。

特性匿名方法Lambda 表达式
关键字使用 delegate使用 =>(Lambda 运算符)
是否需要参数名必须写明参数类型(早期)可推断参数类型,语法更简洁
返回类型必须明确写 return支持表达式体、可隐式返回
表达式体支持❌ 不支持✅ 支持单行表达式直接作为返回值
可读性一般(语法略长)更佳(简洁清晰)

4、捕获外部变量(闭包)

匿名方法delegate)和 Lambda 表达式 都可以捕获外部变量,从而形成所谓的 闭包(Closure)。闭包是指匿名方法或 lambda 表达式可以访问其作用域外定义的变量,并且这个变量会随着函数一起被“捕获”和保存。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 0;
    
            Action increase = delegate {
                counter++;
                Console.WriteLine("Counter = " + counter);
            };
    
            increase();  // Counter = 1
            increase();  // Counter = 2
            increase();  // Counter = 3
        }
    }
}

推荐文档