表达式树:可以使用动态表达式方法构建
本文关键字:表达式 方法 构建 动态 可以使 | 更新日期: 2023-09-27 17:58:49
我是表达式树的新手,一直在尝试构建动态表达式,以便在Linq-to-entities查询中的.Where()
方法中使用。当我显式调用像Expression.Equal(exp, exp)
和Expression.GreaterThan(exp, exp)
这样的Expression方法时,我可以让它全部工作。我想做的是不必对Expression.方法进行硬编码,这样我就可以传递一个带有方法名称的字符串,并用它动态构建。我下面有一个例子。这可能吗?我不知道该怎么办。
static void Main(string[] args)
{
int i = 1;
int? iNullable = 1;
object o = 1;
int j = 2;
ParameterExpression pe1 = Expression.Parameter(typeof(int));
ParameterExpression pe2 = Expression.Parameter(typeof(int));
//explicitly creating expression by calling Expression.Method works fine
Expression call = Expression.Equal(pe1, pe2);
var f = Expression.Lambda<Func<int, int, bool>>(call, pe1, pe2).Compile();
Console.WriteLine(f(i, i));
Console.WriteLine(f((int)iNullable, i));
Console.WriteLine(f(i, (int)o));
Console.WriteLine(f(i, j));
//I want to use a dynamic Expression method instead of Expression.Equal
//so that it could be substituted with Expression.GreaterThan etc.
String expressionMethod = "Equal";
//get the method
MethodInfo method = typeof(Expression)
.GetMethod(expressionMethod,
new[] { typeof(Expression), typeof(Expression) });
//I'm lost ....
Console.ReadKey();
}
原来我只需要调用这个方法!我会提出这个解决方案,以防其他人从中受益。
class Program
{
static void Main(string[] args)
{
int i = 1;
int? iNullable = 1;
object o = 1;
int j = 2;
ParameterExpression pe1 = Expression.Parameter(typeof(int));
ParameterExpression pe2 = Expression.Parameter(typeof(int));
//explicitly creating expression by calling Expression.Method works fine
Expression call = Expression.Equal(pe1, pe2);
var f = Expression.Lambda<Func<int, int, bool>>(call, pe1, pe2).Compile();
Console.WriteLine(f(i, i));
Console.WriteLine(f((int)iNullable, i));
Console.WriteLine(f(i, (int)o));
Console.WriteLine(f(i, j));
//I want to use a dynamic Expression method instead of Expression.Equal
//so that it could be substituted with Expression.GreaterThan etc.
List<String> expressionMethod = new List<string>(){"Equal", "GreaterThan"};
foreach (String s in expressionMethod) DynamicExpression(s, j, i);
Console.ReadKey();
}
static void DynamicExpression(String methodName, int n1, int n2)
{
ParameterExpression pe1 = Expression.Parameter(typeof(int));
ParameterExpression pe2 = Expression.Parameter(typeof(int));
//get the method
MethodInfo method = typeof(Expression)
.GetMethod(methodName,
new[] { typeof(Expression), typeof(Expression) });
//Invoke
Expression dynamicExp = (Expression)method.Invoke(null, new object[] { pe1, pe2 });
var f = Expression.Lambda<Func<int, int, bool>>(dynamicExp, pe1, pe2).Compile();
Console.WriteLine("Result for "
+ n1.ToString() + " "
+ methodName + " " + n2.ToString() + ": " + f(n1, n2));
}
}