【问题标题】:C# Expression trees - combine multiple method callsC# 表达式树 - 组合多个方法调用
【发布时间】:2020-07-05 07:40:42
【问题描述】:

我正在使用 .Net Core 和表达式树。

我有一个 Product 类,其中 LstProp 属性包含由 ';' 分隔的值列表,例如“val1;val2;val3;”:

public class Product
{
  // actually contains list of values separated by ';'
  public string LstProp{get; set;}
}

我想按此属性过滤产品并包含使用表达式树的任何条件。 这个我试过了,还是不行。

 var value="val1;val2"
 var productItem = Expression.Parameter(typeof(Product), "product");
 var prop = Expression.Property(productItem, "LstProp");

 MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
 var values = value.ToString().Split(';');
 Expression predicate = null;
 foreach (var val in values)
 {
    var listPropExpression = Expression.Constant(val);
    var containsExpresion=Expression.Call(listPropExpression, method, property);
    predicate = predicate != null ? Expression.Or(predicate, containsExpresion) : containsExpresion;
 }

所以我尝试为列表中的每个值组合包含函数的调用,但收到有关“BinaryExpression 和 MethodCallExpression 之间没有转换”的错误。

如何将多个方法调用与表达式树结合起来?

【问题讨论】:

    标签: c# linq .net-core expression-trees


    【解决方案1】:

    我找到了解决方案。 我遇到了两个问题:

    1. 参数顺序不正确。 应该是Expression.Call(property, method, listPropExpression); 而不是Expression.Call(listPropExpression, method, property);

    2. 主要问题已通过简单的演员表解决:

      谓词 = 谓词 != null ? (表达式) Expression.Or(predicate, containsExpresion) : containsExpresion;

    结果我得到像product=>product.LstProp.Contains("val1") Or product.LstProp.Contains("val2")这样的表达

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多