为什么这个来自MSDN站点的lambda示例不起作用?

Edw*_*uay 2 c# lambda

我需要对以下lambda示例做些什么才能使它工作?

错误:只能将赋值,调用,递增,递减和新对象表达式用作语句

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
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 6

在C#中将类型定义为方法体语句是不合法的.您需要将该委托移到方法之外,以便进行编译.例如

    delegate int del(int i);

public static void Main(string[] args) {

    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}
Run Code Online (Sandbox Code Playgroud)


Out*_*mer 6

您需要在方法之外声明委托:

class Program
{
    delegate int del(int i);

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

}
Run Code Online (Sandbox Code Playgroud)