1

我是表达式树的新手,一直在尝试构建动态表达式以用于.Where()Linq 中的方法到实体查询。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();

 }
4

1 回答 1

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));
  }
}
于 2013-02-12T06:46:57.307 回答