Tôi đã mở rộng lớp chuỗi cho phương thức Contains
. Tôi đang cố gắng gọi nó trong Expression.Call
, nhưng làm thế nào để vượt qua đối số đúng cách?Gọi Phương thức tĩnh trong expression.call với đối số
Mã: String Có phương pháp:
public static class StringExts
{
public static bool NewContains(this string source, string ValToCheck, StringComparison StrComp)
{
return source.IndexOf(ValToCheck, StrComp) >= 0;
}
}
Trong biểu thức gọi là:
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;
}
}
Lỗi:
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.
Làm thế nào để gọi các tham số trong miContain
cho sau Call()
phương pháp?
Tôi đã cập nhật Mã.
Hơi tắt chủ đề nhưng bạn biết rằng đã có ['String.Contains'] (https://msdn.microsoft.com/en-us/) phương thức library/dy85x1sa (v = vs.110) .aspx)? – Sayse
@Sayse Không có một trong đó có StringComparison như là một đối số bổ sung. –