加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何从Expression>构建Expression>

发布时间:2020-12-15 04:14:06 所属栏目:百科 来源:网络整理
导读:有没有办法构建表达式 Func T,bool来自表达式 Func T? 比如上课 public class MyClass{ public int Prop1{get;set;} public int Prop2{get;set;} public int Prop3{get;set;}} 如果表达式 Func T是()=新的MyClass {Prop2 = 5}然后结果应该是x = x.Prop2 ==
有没有办法构建表达式< Func< T,bool>>来自表达式< Func< T>>?

比如上课

public class MyClass
{
    public int Prop1{get;set;}
    public int Prop2{get;set;}
    public int Prop3{get;set;}
}

如果表达式< Func< T>>是()=>新的MyClass {Prop2 = 5}然后结果应该是x => x.Prop2 == 5

如果表达式< Func< T>>是()=>新的MyClass {Prop1 = 1,Prop3 = 3}然后结果应为x => x.Prop1 == 1&& x.Prop3 == 3

换句话说,是否可以在运行时创建具有任意数量条件的func?

解决方法

像这样:
static Expression<Func<T,bool>> Munge<T>(Expression<Func<T>> selector)
{
    var memberInit = selector.Body as MemberInitExpression;
    if (memberInit == null)
        throw new InvalidOperationException("MemberInitExpression is expected");
    var p = Expression.Parameter(typeof(T),"x");

    Expression body = null;
    foreach (MemberAssignment binding in memberInit.Bindings)
    {
        var comparer = Expression.Equal(
            Expression.MakeMemberAccess(p,binding.Member),binding.Expression);
        body = body == null ? comparer : Expression.AndAlso(body,comparer);
    }
    if (body == null) body = Expression.Constant(true);

    return Expression.Lambda<Func<T,bool>>(body,p);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读