【C#】 C# 匿名函数

Posted by 西维蜀黍 on 2018-02-23, Last Modified on 2021-09-21

1 背景

当我们使用委托(delegate)时,一个委托实例总是与一个有函数名称的函数相互关联。

即,函数的名称被作为一个参数,赋值给委托实例:

// Declare a delegate:
delegate void Del(int x);

// Define a named method:
void DoWork(int k) { /* ... */ }

// Instantiate the delegate using the method as a parameter:
Del d = obj.DoWork;

C# 1.0和此之前,委托仅能被这样表达:

// Declare a delegate.
delegate void Del(string str);

// Declare a method with the same signature as the delegate.
static void Notify(string name)
{
    Console.WriteLine("Notification received for: {0}", name);
}



// Create an instance of the delegate.
Del del1 = new Del(Notify);

C# 2.0中,引入了一种更简洁的表达方式。即,直接用函数的名称赋值给委托实例。

// C# 2.0 provides a simpler way to declare an instance of Del.
Del del2 = Notify;

同时,也可以使用**匿名函数(anonymous method)**来声明并初始化一个委托实例。

匿名函数是一种不包含函数名称(unnamed),且位于内联语句块(inline block)的函数

// Instantiate Del by using an anonymous method.
Del del3 = delegate(string name)
    { Console.WriteLine("Notification received for: {0}", name); };

C# 3.0中,引入了可以用Lambda表达式(Lambda expression)来实例化委托实例的方式。 Lambda表达式从概念上说与匿名函数类似,但更加具有表现力(more expressive)且更简洁(concise)

// Instantiate Del by using a lambda expression.
Del del4 = name =>  { Console.WriteLine("Notification received for: {0}", name); };

2 应用

由于使用匿名函数时,不需要创建一个单独的方法,从而减少了构造委托实例时的代码开销。

比如,当这个方法只会被一次使用到时,使用匿名函数可能会让代码看起来更干净。

void StartThread()
{
    System.Threading.Thread t1 = new System.Threading.Thread
      (delegate()
            {
                System.Console.Write("Hello, ");
                System.Console.WriteLine("World!");
            });
    t1.Start();
}

显然,这里开启了一个新线程,我们要在一个方法中执行这个线程要做某些事情。

Reference