有没有一种方法可以在C#中创建一个表达式,该表达式返回一个常量值,但又具有一个参数?
使用代码,看起来像
var expression = x => 5
因此它应该与Expression<Func<double, double>>
类型匹配。
它可能看起来应该像
ParameterExpression param = Expression.Parameter(typeof(double), "parameter");
ConstantExpression constant = Expression.Constant(0.0);
var expression = Expression.SomeMagic(param, constant);
Expression.Lambda<Func<double, double>>(expression);
答案 0 :(得分:0)
您将参数传递给Expression.Lambda <>():
https://msdn.microsoft.com/en-us/library/dd268052(v=vs.110).aspx
所以您正在寻找类似的东西:
ParameterExpression param = Expression.Parameter(typeof(double), "parameter");
ConstantExpression constant = Expression.Constant(0.0);
var expression = // build the body ...
Expression.Lambda<Func<double, double>>(expression, param);
要返回相同的参数,它就像这样简单:
ParameterExpression param = Expression.Parameter(typeof(double), "parameter");
Expression.Lambda<Func<double, double>>(param, param);
要返回的常数值为:
ParameterExpression param = Expression.Parameter(typeof(double), "parameter");
ConstantExpression constant = Expression.Constant(0.0);
Expression.Lambda<Func<double, double>>(constant, param);