从lambda表达式获取propertyinfo,但使用int失败



获取lambda表达式中所有项的PropertyInfo的最佳方法是什么?

我想在SQL数据库的XML字段上设置一个过滤器。

var FilterBase = new FilterBase<SimpleItemSubObject>()
                    .SetSimpleFilter(x => x.ID, 123)
                    .SetSimpleFilter(x => x.Test.Name, "demo3");

在分析器中,我能够获得Name属性的propertyinfo。

internal IEnumerable<PropertyInfo> GetExpressionList()
{
    return GetPropertyListfor(lambda.Body as MemberExpression);
}
private IEnumerable<PropertyInfo> GetPropertyListfor(MemberExpression body)
{
    var result = new List<PropertyInfo>();
    if (body != null && body.Expression != null)
    {
        result.AddRange(GetPropertyListfor(body.Expression as MemberExpression));
        result.Add((body as MemberExpression).Member as PropertyInfo);
    }
    return result;
}

this将返回propertyinfo如果它是一个字符串属性。但是在int的情况下,分析器会失败,因为lambda添加了一个转换函数。

{x => Convert(x.ID)}

增加了一个转换函数。

那么在这种情况下,获取x.d id的propertyinfo的最佳方法是什么?如何防止使用转换函数

编译器添加Convert表达式的事实表明您正在使用具有object返回类型的非泛型lambda表达式。像这样:

public class FilterBase<T>
{
    public FilterBase<T> SetSimpleFilter(Expression<Func<T, object>> selector, object value)
    {
        // ...
        return this;
    }
}

解决问题的一种方法是使方法通用(类似于LINQ OrderBy):

public FilterBase<T> SetSimpleFilter<V>(Expression<Func<T, V>> selector, V value)

所以没有Convert了。

另一种方法是保持方法不变,并删除第一个Convert(如果有的话):

internal IEnumerable<PropertyInfo> GetExpressionList()
{
    var body = lambda.Body;
    if (body.NodeType == ExpressionType.Convert)
        body = ((UnaryExpression)body).Operand;
    return GetPropertyListfor(body as MemberExpression);
}

最新更新