假设您有一个扩展方法:
public static class StringEx
{
public static bool Like(this string a, string b)
{
return a.ToLower().Contains(b.ToLower());
}
}
你需要这样的东西:
string value = "Something";
ParameterExpression Param = Expression.Parameter(typeof(T), "x");
MemberExpression Member = Expression.Property(Param, "PropertyName");
MethodInfo ToStringMethod = typeof(object).GetMethod("ToString");
MethodInfo ComparerMethod = typeof(StringEx).GetMethod("Like", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new[] { typeof(string), typeof(string) }, null);
MethodCallExpression ToStringExpression = Expression.Call(Member, ToStringMethod);
MethodCallExpression ComparerExpression = Expression.Call(ComparerMethod, ToStringExpression, Expression.Constant(value));
// Here is what you need
Expression<Func<T, bool>> CustomLamdaResult = Expression.Lambda<Func<T, bool>>(body: ComparerExpression , parameters: Param);
测试;)...