Lambda and Expression.Call for an extension method

前端 未结 5 939
野趣味
野趣味 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:25

    You can do like this:

    var like = typeof(StringEx).GetMethod("Like", new[] {typeof(string), typeof(string)});
    
    comparer = Expression.Call(null, like, prop, value);
    

    You can pass prop as first parameter and value as second parameter like above.

    Maybe you will need to get a complete query before apply an extension method.

    0 讨论(0)
  • 2021-01-17 23:26

    I am not sure, but you can only get an extension method from the static class using reflection. Extension methods are not truly added to the class, therefore can't be retrieved with GetMethod.

    0 讨论(0)
  • 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<bool>) Expression.Lambda(comparer).Compile();
    bool isEquals = vvv.Invoke();
    
    0 讨论(0)
  • 2021-01-17 23:38

    Use

    var like = typeof(StringEx).GetMethod("Like", new[] {typeof(string),typeof(string)});
    

    ie. retrieve it from the extending type, not from the extended type.

    0 讨论(0)
  • 2021-01-17 23:46

    If you want to get your extension method worked you must do like this:

    string str = "some string";
    str.Like("second string");
    
    0 讨论(0)
提交回复
热议问题