2011-06-08 78 views
3

可能重复:
C# Lambda (=>)C#中“=>”的含义是什么?

例如

Messenger.Default.Register<AboutToCloseMessage>(this, (msg) => 
     { 
      if (msg.TheContainer == this.MyContainer) // only care if my container. 
      { 
       // decide whether or not we should cancel the Close 
       if (!(this.MyContainer.CanIClose)) 
       { 
        msg.Execute(true); // indicate Cancel status via msg callback. 
       } 
      } 
     }); 
+10

@Shakti辛格:你能告诉我们如何搜索'=>'符号? – BoltClock 2011-06-08 13:19:21

+6

@Shakti Singh:如果Rdeluca知道'=>'的意思是“lambda表达式”,他首先不会问。 – BoltClock 2011-06-08 13:24:03

+1

是啊..不知道它叫做lambda还是我会搜索它。谢谢! – Rdeluca 2011-06-08 13:46:50

回答

1

这是一个lambda,它可以让你轻松创建功能。

在你的榜样,你也可以这样写:

Messenger.Default.Register<AboutToCloseMessage>(this, delegate(Message msg) 
{ 
    if (msg.TheContainer == this.MyContainer) // only care if my container. 
    { 
     // decide whether or not we should cancel the Close 
     if (!(this.MyContainer.CanIClose)) 
     { 
      msg.Execute(true); // indicate Cancel status via msg callback. 
     } 
    } 
}); 

甚至

Messenger.Default.Register<AboutToCloseMessage>(this, foobar); 

// somewhere after // 
private void foobar(Message msg) 
{ 
    if (msg.TheContainer == this.MyContainer) // only care if my container. 
    { 
     // decide whether or not we should cancel the Close 
     if (!(this.MyContainer.CanIClose)) 
     { 
      msg.Execute(true); // indicate Cancel status via msg callback. 
     } 
    } 
} 
0

这是一个lambda表达式(http://msdn.microsoft.com/zh-cn/library/bb397687.aspx)。

0

其一个LAMDA表达(功能参数)=> {函数体}

类型参数可以指定,但编译通常只是解释。

0

这就是你如何在C#中定义lambda。 msg是传递给lambda方法的参数,其余部分是方法的主体。

那相当于是这样的:

Messenger.Default.Register<AboutToCloseMessage>(this, SomeMethod); 

void SomeMethod(SomeType msg) 
{ 
    if (msg.TheContainer == this.MyContainer) // only care if my container. 
    { 
     // decide whether or not we should cancel the Close 
     if (!(this.MyContainer.CanIClose)) 
     { 
      msg.Execute(true); // indicate Cancel status via msg callback. 
     } 
    } 
}