我正在执行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);
使用表达式树(不起作用)...
// Build a Func<> using an Expression Tree
ParameterExpression numParam = Expression.Parameter(typeof(int));
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numAddFive = Expression.Add(numParam, five);
Func<int, int> func2 =
Expression.Lambda<Func<int, int>>(
numAddFive,
new ParameterExpression[] { numParam }).Compile();
// Convert to an Expression using NJection (EXCEPTION ON NEXT LINE)
// ToExpr is trying to access func2.Method.DeclaringType.FullName(DeclaringType is null)
Expression<Func<int, int>> exp2 = ToExpr<Func<int, int>>(func2);
// Convert it back to a Func<>
Func<int, int> func2b = exp2.Compile();
// Run the Func<>
int result2 = func2b(100);
我不知道NJection库的用途是什么,因为他们的网站已经关闭并且Codeplex没有可用的源代码。
如果只需要获取一个Expression
可以编译回该函数的函数,则可以自己创建它。例如:
static Expression<T> ToExpr<T>(T func)
{
var type = typeof(T);
var method = type.GetMethod("Invoke"); // Delegate.Invoke() has parameters types matching delegate parameters types
var pars = method.GetParameters()
.Select(pi => Expression.Parameter(pi.ParameterType))
.ToArray();
return Expression.Lambda<T>(
Expression.Call(Expression.Constant(func), method, pars),
pars
);
}
这样ToExpr
,您上面的代码即可编译并运行而不会出现问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句