A.P*_*P.S 9 .net c# 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;
}
}
Run Code Online (Sandbox Code Playgroud)
在表达式中调用为:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
System.Core.dll中发生了类型为"System.ArgumentException"的未处理异常.附加信息:静态方法需要null实例,非静态方法需要非null实例.
如何调用miContain以下Call()方法的参数?
我已经更新了守则.
Pat*_*man 13
您没有指定所有参数.如果为所有人创建表达式,它可以工作:
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");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7444 次 |
| 最近记录: |