2

我正在尝试编写一个可以这样调用的方法:

var myCommand = Command.Where(x => x.Name == "grep" && x.Switch == "x");

我想要做的是解析结果表达式,如下所示:

public static string FindBy(Expression<Func<T, bool>>  expression)
{
    var condition1Key = ? //condition1Key = "Name"
    var condition1Value = ? //condition1Value = "grep"
    var condition2Key = ? //condition1Key = "Switch"
    var condition2Value = ? //condition1Value = "x"
    
   return string.Format("Looking for commands with {0} = {1} and {2} = {3}",
                         condition1Key, condition1Value, 
                         condition2Key, condition2Value);
}

我确实找到了这篇文章,但它已经很老了,从未收到过正确的答案。

我如何解析传入Expression的内容以提取我需要的内容?

4

2 回答 2

2

您可以解析Expression树。这是 MSDN 的一个基本示例:http: //msdn.microsoft.com/en-us/library/bb397951.aspx

更多来自博客文章:http: //blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx

在这里有一个很好的答案:https ://stackoverflow.com/a/239359/29093

于 2012-04-27T00:49:02.387 回答
2

如果您按照您提到的 SO 线程中的链接,您将到达MSDN 条目 for expressions。特别是,在“解析表达式树”部分下,以下示例应该会有所帮助:

// Create an expression tree.
Expression<Func<int, bool>> exprTree = num => num < 5;

// Decompose the expression tree.
ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];
BinaryExpression operation = (BinaryExpression)exprTree.Body;
ParameterExpression left = (ParameterExpression)operation.Left;
ConstantExpression right = (ConstantExpression)operation.Right;

Console.WriteLine("Decomposed expression: {0} => {1} {2} {3}",
              param.Name, left.Name, operation.NodeType, right.Value);

// This code produces the following output:
// Decomposed expression: num => num LessThan 5    

您甚至可以创建一个类来使在树上的行走更容易:如何:实现表达式树访问器

于 2012-04-27T00:58:30.180 回答