返回嵌套的通用Expression< Func< T,bool>.

返回嵌套的通用Expression< Func< T,bool>.

问题描述:

错误消息是找不到类型或名称空间名称'T'."

The error message is "The type or namespace name 'T' could not be found."

???

public static Expression<Func<T, bool>> MakeFilter(string prop, object val)
{
    ParameterExpression pe = Expression.Parameter(typeof(T), "p");
    PropertyInfo pi = typeof(T).GetProperty(prop);
    MemberExpression me = Expression.MakeMemberAccess(pe, pi);
    ConstantExpression ce = Expression.Constant(val);
    BinaryExpression be = Expression.Equal(me, ce);
    return Expression.Lambda<Func<T, bool>>(be, pe);
}

相关链接:

使用反射来寻址Linqed属性

>: //social.msdn.microsoft.com/forums/zh-CN/linqprojectgeneral/thread/df9dba6e-4615-478d-9d8a-9fd80c941ea2/

在运行时创建通用Func< T>

您需要使方法本身具有通用性:

You need to make the method itself generic:

public static Expression<Func<T, bool>> MakeFilter<T>(string prop, object val)
                                                  -+-
                                                   ^
                                                   +- this