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

时间:2013-04-23 14:04:37

标签: c# expression expression-trees func

当我有这个时,

public static object Create()
{
    return new object();
}

这有效:

var m = typeof(Class).GetMethod("Create");
var e = Expression.Call(m);
Func<object> f = Expression.Lambda<Func<object>>(e).Compile();

但是当我有这个时,

public static object Create(Type t)
{
    return new object();
}

这失败了:

var m = typeof(Class).GetMethod("Create");
var e = Expression.Call(m, Expression.Parameter(typeof(Type)));
var t = Expression.Parameter(typeof(Foo));
Func<object> f = Expression.Lambda<Func<object>>(e, t).Compile();

我得到 System.Core.dll中发生了'System.ArgumentException'类型的未处理异常。附加信息:为lambda声明提供的参数数量不正确。参数t只是虚拟类型Foo的表达式。我认为这无关紧要。我在哪里错了?

1 个答案:

答案 0 :(得分:14)

问题是你说你想要使用一个参数 - 但是你实际上并没有在任何地方提供它来指定它。您正在创建两个不同类型的ParameterExpression,然后尝试将结果转换为Func<object> - 它根本没有任何参数。你想要这样的东西:

var m = typeof(Class).GetMethod("Create");
var p = Expression.Parameter(typeof(Type), "p");
var e = Expression.Call(m, p);
Func<Type, object> f = Expression.Lambda<Func<Type, object>>(e, p).Compile();

请注意,ParameterExpression方法和Expression.Call方法的参数列表中使用了相同的Expression.Lambda