使用参数在expression.call中调用静态方法

时间:2015-08-10 11:14:22

标签: c# .net lambda delegates expression-trees

我扩展了Contains方法的字符串类。我试图在Expression.Call中调用它,但是如何正确地传递参数?

代码:String包含方法:

public static class StringExts
{
    public static bool NewContains(this string source, string ValToCheck, StringComparison StrComp)
    {
        return source.IndexOf(ValToCheck, StrComp) >= 0;
    }
}

在表达式中呼叫:

public class Person { public string Name {get; set;} }

public class Persons { 
    public List<Person> lstPersons {get; set;} 
    public Persons() {
      lstPersons = new List<Person>();    
    }
}

public class Filter 
{
    public string Id { get; set; }
    public Operator Operator { get; set; }
    public string value { get; set; }
}

public void Main()
{
   //Get the json.
   //"Filters": [{"id": "Name", "operator": "contains", "value": "Microsoft"}]

    Filter Rules = JsonConvert.DeserializeObject<Filter>(json);

   // Get the list of person firstname.
    List<Person> lstPerson = GetFirstName();

   ParameterExpression param = Expression.Parameter(typeof(Person), "p");
   Expression exp = null;

   exp = GetExpression(param, rules[0]);

   //get all the name contains "john" or "John"
   var filteredCollection = lstPerson.Where(exp).ToList();

}

private Expression GetExpression(ParameterExpression param, Filter filter){
   MemberExpression member = Expression.Property(param, filter.Id);
   ConstantExpression constant = Expression.Constant(filter.value);

   Expression bEXP = null;

   switch (filter.Operator)
    {
         case Operator.contains:
           MethodInfo miContain = typeof(StringExts).GetMethod("NewContains", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
           return  Expression.Call(miContain, member, constant , Expression.Constant(StringComparison.OrdinalIgnoreCase));; 
           break;
    }
 }

错误:

  

System.Core.dll中出现未处理的“System.ArgumentException”类型异常。附加信息:静态方法需要null实例,非静态方法需要非null实例。

如何在miContain中调用Call()方法中的参数?

我已更新守则。

2 个答案:

答案 0 :(得分:11)

您没有指定所有参数。如果为所有人创建表达式,它可以工作:

ParameterExpression source = Expression.Parameter(typeof(string));
string ValToCheck = "A";
StringComparison StrComp = StringComparison.CurrentCultureIgnoreCase;

MethodInfo miContain = typeof(StringExts).GetMethod("NewContains", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
var bEXP = Expression.Call(miContain, source, Expression.Constant(ValToCheck), Expression.Constant(StrComp));

var lambda = Expression.Lambda<Func<string, bool>>(bEXP, source);

bool b = lambda.Compile().Invoke("a");

答案 1 :(得分:0)

您没有指定足够的参数(2对3)。 NewContains有三个论点。

此外,由于此方法不是实例方法,因此无法设置此参数。 This overload looks better.

您可能应该检查overload list。这就是我在事先不知情的情况下找到正确答案的方法。