Lambda and Expression.Call for an extension method

前端 未结 5 938
野趣味
野趣味 2021-01-17 23:08

I need to implement an expression for a method like here:

var prop = Expression.Property(someItem, \"Name\"); 
var value = Expression.Constant(someConstant);         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 23:27

    Try this

    public class Person
    {
        public string Name { get; set; }
    }
    public static class StringEx
    {
        public static bool Like(this string a, string b)
        {
            return a.ToLower().Contains(b.ToLower());
        }
    }
    
    Person p = new Person(){Name = "Me"};
    var prop = Expression.Property(Expression.Constant(p), "Name");
    var value = Expression.Constant("me");
    var like = typeof(StringEx).GetMethod("Like", BindingFlags.Static
                            | BindingFlags.Public | BindingFlags.NonPublic);
    var comparer = Expression.Call(null, like, prop, value );
    
    var vvv = (Func) Expression.Lambda(comparer).Compile();
    bool isEquals = vvv.Invoke();
    

提交回复
热议问题