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

前端之家收集整理的这篇文章主要介绍了c# – 使用参数在expression.call中调用静态方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经扩展了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;
    }
 }

错误

An unhandled exception of type ‘System.ArgumentException’ occurred in System.Core.dll.Additional information: Static method requires null instance,non-static method requires non-null instance.

如何调用miContain中的参数来跟随Call()方法

我已经更新了守则.

解决方法

您没有指定所有参数.如果为所有人创建表达式,它可以工作:
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");
原文链接:https://www.f2er.com/csharp/91419.html

猜你在找的C#相关文章