我正在做一个Func - > Expression - > Func转换.如果我从方法(下面的第一个示例)创建Func <>(),它可以正常工作,但是如果我使用表达式树(第二个示例)创建函数,则在访问func2.Method.DeclaringType.FullName时它会因NullReferenceException而失败.这是因为DeclaringType为null.(NJection使用反射,所以我认为这就是它需要DeclaringType的原因.)
如何为通过编译表达式树创建的Func <>填写DeclaringType类型?(也许它不可能?)DeclaringType在第一个例子中设置.
使用方法中的Func <> ...(效果很好)
// Build a Func<>
Func<int, int> add = Add;
// Convert it to an Expression using NJection Library
Expression<Func<int, int>> expr = ToExpr<Func<int, int>>(add);
// Convert it back to a Func<>
Func < int, int> func = expr.Compile();
// Run the Func<>
int result = func(100);
Run Code Online (Sandbox Code Playgroud)
使用表达式树(不起作用)......
// Build a Func<> using an Expression Tree
ParameterExpression numParam = Expression.Parameter(typeof(int)); …Run Code Online (Sandbox Code Playgroud)