请看一下我的代码:我正在尝试使用表达式树创建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(); } }
我无法弄清楚什么是错的,我在哪里做错了.提前致谢.
解决方法
您必须在Expression.Lambda的’params ParameterExpression [] parameters’部分中指定引擎
var m = Expression.Lambda<Func<Engine,engine),engine)