我需要对以下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
}
}
}
答案 0 :(得分:6)
在C#中将类型定义为方法体语句是不合法的。您需要将该委托移到方法之外,以便进行编译。例如
delegate int del(int i);
public static void Main(string[] args) {
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
答案 1 :(得分:6)
您需要在方法之外声明委托:
class Program
{
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
}