【发布时间】:2015-11-02 06:45:08
【问题描述】:
我已经为Contains 方法扩展了字符串类。我正在尝试在Expression.Call 中调用它,但是如何正确传递参数?
代码:字符串包含方法:
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”类型的未处理异常。附加信息:静态方法需要空实例,非静态方法需要非空实例。
如何调用miContain中的参数以跟随Call()方法?
我已经更新了代码。
【问题讨论】:
-
有点跑题但你知道已经有一个
String.Contains方法吗? -
@Sayse 没有一个将 StringComparison 作为附加参数。
标签: c# .net lambda delegates expression-trees