返回嵌套的通用表达式<func <t,bool =“”>&gt; </func <t,>

时间:2009-05-13 19:43:56

标签: c# .net linq lambda

错误消息是“无法找到类型或命名空间名称'T'。”

???

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

相关链接:

Using reflection to address a Linqed property

http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/df9dba6e-4615-478d-9d8a-9fd80c941ea2/

Runtime creation of generic Func<T>

3 个答案:

答案 0 :(得分:10)

您需要使方法本身通用:

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

答案 1 :(得分:3)

没有为您的方法定义泛型参数。您应该定义一个(MakeFilter<T>):

public static Expression<Func<T, bool>> MakeFilter<T>(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);
}

答案 2 :(得分:2)

该方法需要声明为通用(MakeFilter<T>):

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

否则,调用者还能如何指定T是什么?