为lambda声明提供的参数数量不正确

时间:2011-01-21 12:31:48

标签: c# .net lambda expression-trees

请查看我的代码:我正在尝试使用表达式树创建myCar

我在此行ArgumentException上获得var m = Expression.Lambda<Func<Engine,... 消息是为lambda声明提供的参数数量不正确

public class Engine
{
    public string Name { get; private set; }
    public Engine(string name)
    {
        Name = name;
    }
}
public class Car
{
    private readonly Engine engine;
    public Car(Engine engine)
    {
        this.engine = engine;
    }
    public string GetEngineName(){return engine.Name;}
}
class Program
{
    static void Main(string[] args)
    {
        var ci = typeof (Car).GetConstructor(new[] {typeof (Engine)});

        var engine = Expression.Parameter(typeof (Engine));

        var m = Expression.Lambda<Func<Engine,Car>>(Expression.New(ci, engine))
                          .Compile();

        var myCar = m(new Engine("TDI 2.0"));
        var s = myCar.GetEngineName();
    }
}

我无法弄清楚错误是什么以及我在哪里犯了错误。提前谢谢。

1 个答案:

答案 0 :(得分:13)

您必须在Expression.Lambda的'params ParameterExpression []参数'部分指定引擎

var m = Expression.Lambda<Func<Engine, Car>>(Expression.New(ci, engine), engine)