方法为“选择”的动态表达式树

时间:2018-08-17 11:29:35

标签: c# linq reflection expression expression-trees

我正在尝试使用表达式树->

构建以下lambda表达式
info => info.event_objects.Select(x => x.object_info.contact_info)

我做了很多研究,并在StackOverflow上找到了一些答案。 This one帮助我建立了

info => 
     info.event_objects.Any(x => x.object_info.contact_info.someBool == true)

如您所见,'Any'方法很容易获得。

var anyMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == "Any" 
&& m.GetParameters().Length == 2);
anyMethod = anyMethod.MakeGenericMethod(childType);

主要问题在于方法“选择”。如果您尝试将名称“ Any”更改为“ Select”,则会出现以下异常:

var selectMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == 
"Select" && m.GetParameters().Length == 2);
selectMethod = selectMethod.MakeGenericMethod(childType);
  

其他信息:序列包含多个匹配元素

我尝试过的另一种方法:

MethodInfo selectMethod = null;
foreach (MethodInfo m in typeof(Enumerable).GetMethods().Where(m => m.Name 
  == "Select"))
    foreach (ParameterInfo p in m.GetParameters().Where(p => 
           p.Name.Equals("selector")))
        if (p.ParameterType.GetGenericArguments().Count() == 2)
            selectMethod = (MethodInfo)p.Member;

似乎可行,但随后出现异常:

navigationPropertyPredicate = Expression.Call(selectMethod, parameter, 
navigationPropertyPredicate);

 Additional information: Method 
 System.Collections.Generic.IEnumerable`1[TResult] Select[TSource,TResult] 
 (System.Collections.Generic.IEnumerable`1[TSource], 
 System.Func`2[TSource,TResult]) is a generic method definition> 

之后,我尝试使用:

selectMethod = selectMethod.MakeGenericMethod(typeof(event_objects), 
typeof(contact_info));

实际上,这没有帮助。

这是我的完整代码

 public static Expression GetNavigationPropertyExpression(Expression parameter, params string[] properties)
    {
        Expression resultExpression = null;
        Expression childParameter, navigationPropertyPredicate;
        Type childType = null;

        if (properties.Count() > 1)
        {
            //build path
            parameter = Expression.Property(parameter, properties[0]);
            var isCollection = typeof(IEnumerable).IsAssignableFrom(parameter.Type);
            //if it´s a collection we later need to use the predicate in the methodexpressioncall
            if (isCollection)
            {
                childType = parameter.Type.GetGenericArguments()[0];
                childParameter = Expression.Parameter(childType, "x");
            }
            else
            {
                childParameter = parameter;
            }
            //skip current property and get navigation property expression recursivly
            var innerProperties = properties.Skip(1).ToArray();
            navigationPropertyPredicate = GetNavigationPropertyExpression(childParameter, innerProperties);
            if (isCollection)
            {
                //var selectMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == "Select" && m.GetParameters().Length == 2);
                //selectMethod = selectMethod.MakeGenericMethod(childType);
                MethodInfo selectMethod = null;
                foreach (MethodInfo m in typeof(Enumerable).GetMethods().Where(m => m.Name == "Select"))
                    foreach (ParameterInfo p in m.GetParameters().Where(p => p.Name.Equals("selector")))
                        if (p.ParameterType.GetGenericArguments().Count() == 2)
                            selectMethod = (MethodInfo)p.Member;

                navigationPropertyPredicate = Expression.Call(selectMethod, parameter, navigationPropertyPredicate);
                resultExpression = MakeLambda(parameter, navigationPropertyPredicate);
            }
            else
            {
                resultExpression = navigationPropertyPredicate;
            }
        }
        else
        {
            var childProperty = parameter.Type.GetProperty(properties[0]);
            var left = Expression.Property(parameter, childProperty);
            var right = Expression.Constant(true, typeof(bool));
            navigationPropertyPredicate = Expression.Lambda(left);
            resultExpression = MakeLambda(parameter, navigationPropertyPredicate);
        }
        return resultExpression;
    }


    private static Expression MakeLambda(Expression parameter, Expression predicate)
    {
        var resultParameterVisitor = new ParameterVisitor();
        resultParameterVisitor.Visit(parameter);
        var resultParameter = resultParameterVisitor.Parameter;
        return Expression.Lambda(predicate, (ParameterExpression)resultParameter);
    }

    private class ParameterVisitor : ExpressionVisitor
    {
        public Expression Parameter
        {
            get;
            private set;
        }
        protected override Expression VisitParameter(ParameterExpression node)
        {
            Parameter = node;
            return node;
        }
    }


    [TestMethod]
    public void TestDynamicExpression()
    {
        var parameter = Expression.Parameter(typeof(event_info), "x");
        var expression = GetNavigationPropertyExpression(parameter, "event_objects", "object_info", "contact_info");
    }

编辑:不幸的是,我已经尝试过this个问题的答案,但这似乎没有用

2 个答案:

答案 0 :(得分:0)

  

“其他信息:序列包含多个匹配元素”

与“ Any()”不同,对于“ Select()”,有两个带有两个参数的重载:

  1. Select<TS, TR>(IE<TS> source, Func<TS, TR> selector)
  2. Select<TS, TR>(IE<TS> source, Func<TS, int, TR> selector) (采用“(item,index)=>”选择器lambda)

由于您的代码无论如何已经依赖于“深奥的知识”,因此只需选择其中的第一个即可。

var selectMethod = typeof(Enumerable).GetMethods()
        .First(m => m.Name == nameof(Enumerable.Select) 
                 && m.GetParameters().Length == 2);

答案 1 :(得分:0)

您可以避免使用两个Expression.Call方法重载之一(对于static来说是一个,而通过反射来找到正确的泛型方法重载(这已经很复杂并且容易出错,正如您已经注意到的那样)。 instance个方法)接受string methodNameType[] typeArguments

由于缺乏清晰的表达和lambda表达构建的分离,当前的实现也过于复杂,并存在其他问题。

这是一个正确的工作实现:

public static LambdaExpression GetNavigationPropertySelector(Type type, params string[] properties)
{
    return GetNavigationPropertySelector(type, properties, 0);
}

private static LambdaExpression GetNavigationPropertySelector(Type type, string[] properties, int depth)
{
    var parameter = Expression.Parameter(type, depth == 0 ? "x" : "x" + depth);
    var body = GetNavigationPropertyExpression(parameter, properties, depth);
    return Expression.Lambda(body, parameter);
}

private static Expression GetNavigationPropertyExpression(Expression source, string[] properties, int depth)
{
    if (depth >= properties.Length)
        return source;
    var property = Expression.Property(source, properties[depth]);
    if (typeof(IEnumerable).IsAssignableFrom(property.Type))
    {
        var elementType = property.Type.GetGenericArguments()[0];
        var elementSelector = GetNavigationPropertySelector(elementType, properties, depth + 1);
        return Expression.Call(
            typeof(Enumerable), "Select", new Type[] { elementType, elementSelector.Body.Type },
            property, elementSelector);
    }
    else
    {
        return GetNavigationPropertyExpression(property, properties, depth + 1);
    }
}

第一个是公共方法。它在内部使用接下来的两个私有方法来递归地构建所需的lambda。如您所见,我在构建lambda表达式和用作lambda主体的表达式之间进行了区分。

测试:

var selector = GetNavigationPropertySelector(typeof(event_info), 
    "event_objects", "object_info", "contact_info");

结果:

x => x.event_objects.Select(x1 => x1.object_info.contact_info)