naw*_*fal 4 c# expression func expression-trees
当我有这个,
public static object Create()
{
return new object();
}
Run Code Online (Sandbox Code Playgroud)
这工作:
var m = typeof(Class).GetMethod("Create");
var e = Expression.Call(m);
Func<object> f = Expression.Lambda<Func<object>>(e).Compile();
Run Code Online (Sandbox Code Playgroud)
但是,当我有这个,
public static object Create(Type t)
{
return new object();
}
Run Code Online (Sandbox Code Playgroud)
这失败了:
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();
Run Code Online (Sandbox Code Playgroud)
我得到System.Core.dll中发生的类型为"System.ArgumentException"的未处理异常.附加信息:为lambda声明提供的参数数量不正确.该参数t只是虚拟类型的表达式Foo.我认为这无关紧要.我在哪里错了?
Jon*_*eet 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();
Run Code Online (Sandbox Code Playgroud)
请注意,方法和方法ParameterExpression的参数列表中使用相同Expression.Call的Expression.Lambda方法.
| 归档时间: |
|
| 查看次数: |
3373 次 |
| 最近记录: |