2011-06-08 120 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. 
     } 
    } 
}