什么是+ =(o,arg)=>实际上实现了什么?

Tim*_*sor 15 c#

很抱歉要问所有人,但我是一个老手Vb.net的家伙谁转移到c#.我有以下代码片段似乎在触发postAsync方法(在本例中)时激活.我只是不明白代码在做什么(如下): -

app.PostCompleted +=
    (o, args) =>
    {
        if (args.Error == null)
        {
            MessageBox.Show("Picture posted to wall successfully.");
        }
        else
        {
            MessageBox.Show(args.Error.Message);
        }
    };
Run Code Online (Sandbox Code Playgroud)

如果有人能解释+ =(o,args)=>实际上是什么,我会非常感激....

提前谢谢了.蒂姆

Eti*_*tel 27

(o,args) =>定义一个lambda表达式,它接受两个名为o和的参数args.这些参数的类型是根据类型推断的PostCompleted(如果PostCompletedEventHandler,那么它们将分别是类型ObjectEventArgs).然后表达式的主体跟随=>.

结果将被添加为处理程序PostCompleted.

因此,这是一种不那么冗长的写作方式:

app.PostCompleted += delegate(object o, EventArgs args)
{
    // ...
};
Run Code Online (Sandbox Code Playgroud)

这是一个简写:

void YourHandler(object o, EventArgs args)
{
    // ...
}

// ...

app.PostCompleted += YourHandler;
Run Code Online (Sandbox Code Playgroud)

  • 这本身就是`app.PostCompleted + = new EventHandler(YourHandler);`的简写. (8认同)
  • @Sung我认为这正是他所说的. (4认同)

Cod*_*ked 8

这是使用lambda表达式为PostCompleted事件添加的处理程序.它类似于

  app.PostCompleted += MyHandler;

  // ...

  private void MyHandler(object sender, EventArgs e) {
      // ...
  }
Run Code Online (Sandbox Code Playgroud)

但是在使用lambda表达式时,您无法轻松分离处理程序.


ret*_*one 5

它是为POST完成事件定义事件处理程序的委托的简写:

app.PostCompleted += delegate(object o, EventArgs args) { 
    // ...
};
Run Code Online (Sandbox Code Playgroud)

另请参见匿名方法.