我是表达树的新手,并且一直在尝试构建动态表达式,以便在Linq中的.Where()
方法中使用实体查询。当我明确调用像Expression.Equal(exp, exp)
和Expression.GreaterThan(exp, exp)
这样的表达式方法时,我可以全部工作。我想要做的是不必对Expression.Method进行硬编码,以便我可以传递一个带有方法名称的字符串并使用它动态构建。我有一个例子如下。这可能吗?我不知道如何继续。
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();
}
答案 0 :(得分:2)
原来我只需要调用该方法!我会提出这个解决方案,以防其他任何人从中受益。
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));
}
}