C# - 匿名方法 Anonymous Method
顾名思义,匿名方法就是没有名字的方法。 C# 中的匿名方法可以使用委托关键字定义,并且可以分配给委托类型的变量。
csharp
using System;
namespace ConsoleApp1
{
public delegate void Print(int value);
class Program
{
static void Main(string[] args)
{
Print print = delegate (int val)
{
Console.WriteLine("在匿名方法里面. Value: {0}", val);
};
print(100);// 在匿名方法里面. Value: 100
}
}
}匿名方法可以访问在函数外中定义的变量。
csharp
using System;
namespace ConsoleApp1
{
public delegate void Print(int value);
class Program
{
static void Main(string[] args)
{
int i = 10;
Print print = delegate (int val)
{
val += i;
Console.WriteLine("在匿名方法里面. Value: {0}", val);
};
print(100);// 在匿名方法里面. Value: 110
}
}
}匿名方法也可以传递给带有委托参数的方法。
在以下示例中, PrintHelperMethod() 接受 Print 委托的第一个参数:
csharp
using System;
namespace ConsoleApp1
{
public delegate void Print(int value);
class Program
{
public static void PrintHelperMethod(Print printDel, int val)
{
val += 10;
printDel(val); // 匿名方法: 110
}
static void Main(string[] args)
{
PrintHelperMethod(delegate (int val) { Console.WriteLine("匿名方法: {0}", val); }, 100);
}
}
}输出
shell
匿名方法: 110匿名方法可以用作事件处理程序:
csharp
class Program
{
public static event Action<int> changed;
static void Main(string[] args)
{
//注册事件处理程序同常是在其它类里面,这边只是演示匿名方法
changed += delegate (int i) { Console.WriteLine($"事件内:{i}"); };
changed += delegate (int i) { Console.WriteLine($"第二个事件内:{i}"); };
changed(10);
//事件内:10
//第二个事件内:10
}
}输出
csharp
事件内:10
第二个事件内:10C# 3.0 引入了 lambda 表达式,它也像匿名方法一样工作。
匿名方法限制
- 它不能包含跳转语句,如 goto、break 或 continue。
- 它不能访问外部方法的 ref 或 out 参数。
- 它不能拥有或访问不安全的代码。
- 它不能用于 is 运算符的左侧。
要记住的要点:
- 匿名方法可以使用delegate关键字定义
- 匿名方法必须分配给委托。
- 匿名方法可以访问外部变量或函数。
- 匿名方法可以作为参数传递。
- 匿名方法可以用作事件处理程序。
