2009-03-10 14 views
2

次のラムダの例を使用するには、どうすればよいですか?MSDNサイトのこのラムダの例はなぜ機能しませんか?

ERROR:のみ割り当て、呼び出し、インクリメント、デクリメント、および新しいオブジェクト式は、ステートメント

http://msdn.microsoft.com/en-us/library/bb397687.aspx

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Linq.Expressions; 

namespace TestLambda 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      delegate int del(int i); 
      del myDelegate = x => x * x; 
      int j = myDelegate(5); //j = 25 
     } 

    } 

} 
+0

JaredParがそれをカバーしています。 MSDNサンプルは省略されることがあります。おそらく、省略記号はここではっきりしていたでしょう... –

答えて

6

については、メソッドの外でデリゲートを宣言する必要があります:

class Program 
{ 
    delegate int del(int i); 

    static void Main(string[] args) 
    {    
     del myDelegate = x => x * x; 
     int j = myDelegate(5); //j = 25 
    } 

} 
6

これは、メソッド本体としてタイプを定義するために法的ではありませんとして使用することができますC#のステートメントそれをコンパイルするには、デリゲートをメソッド外に移動する必要があります。例

delegate int del(int i); 

public static void Main(string[] args) { 

    del myDelegate = x => x * x; 
    int j = myDelegate(5); //j = 25 
} 
+0

さらに良い点は、Func ; -p –

+0

@Marc、yesを使用するだけです。基本的に、アセンブリレベルでFunc <>、Action <>をtypedefできれば、単純なFunc <>、Action <>を実行したときに、新しいデリゲート型を作成できないようにすることができます。 – JaredPar

関連する問題