我刚刚开始使用表达式树,所以我希望这是有道理的。我试图创建一个表达式树来表示:
t => t.SomeProperty.Contains("stringValue");
到目前为止,我已经:
private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string propertyValue) { var parameterExp = Expression.Parameter(typeof(T), "type"); var propertyExp = Expression.Property(parameter, propertyName); var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :) ... return Expression.Lambda<Func<string, bool>>(containsMethodExp, parameterExp); //then something like this }
我只是不知道如何引用String.Contains()方法。
帮助表示赞赏。
就像是:
class Foo { public string Bar { get; set; } } static void Main() { var lambda = GetExpression<Foo>("Bar", "abc"); Foo foo = new Foo { Bar = "aabca" }; bool test = lambda.Compile()(foo); } static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue) { var parameterExp = Expression.Parameter(typeof(T), "type"); var propertyExp = Expression.Property(parameterExp, propertyName); MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var someValue = Expression.Constant(propertyValue, typeof(string)); var containsMethodExp = Expression.Call(propertyExp, method, someValue); return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp); }
您可能会发现这很有帮助。