作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在做一个 Func -> Expression -> Func 转换。如果我从一个方法(下面的第一个示例)创建 Func<>(),它工作正常,但是如果我使用表达式树(第二个示例)创建函数,它会在访问 时失败并出现 NullReferenceException>func2.Method.DeclaringType.FullName。这是因为 DeclaringType 为空。 (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
,你上面的代码就可以毫无问题地编译和运行了。
关于c# - 有没有办法在表达式树中设置 'DeclaringType'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34277542/
我是一名优秀的程序员,十分优秀!