c# - Lambda 和 Expression.Call 扩展方法

标签 c# .net lambda extension-methods expression-trees

我需要为此处的方法实现一个表达式:

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

var contains = typeof(string).GetMethod("Contains", new[] {typeof(string)});
var expression = Expression.Call(prop, contains, value);

但是对于我的扩展方法:

public static class StringEx
{
    public static bool Like(this string a, string b)
    {
        return a.ToLower().Contains(b.ToLower());
    }
}

不幸的是,下一个代码为参数“method”抛出一个 ArgumentNullException:

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

我做错了什么?

最佳答案

试试这个

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();

关于c# - Lambda 和 Expression.Call 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8337774/

相关文章:

c# - C#中的VirtualAlloc分配大内存

c# - 如何为 C# 项目定义环境变量

c# - Azure 通知中心。远程服务器返回错误: (404) Not Found.找不到NotificationId

c# - 计算点击次数 C#

c# - 实现一维碰撞检测的最佳方法是什么?

c# - 如何避免 json 对象中的逗号?

c# - MVVM,我是否必须将每个命令保留在自己的类中?

c# - Entity Framework 过滤器 "Expression<Func<T, bool>>"

R匿名函数: capture variables by value

C++ Vector Sort 方法编译失败,返回预期的表达式