将表达式解析为参数

时间:2012-04-27 00:43:54

标签: c# lambda

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

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

我确实找到this post,但它已经很老了,从来没有得到正确答案。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

如果您按照上述SO线程中的链接进行操作,则会到达MSDN entry 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    

您甚至可以创建一个类,以便更轻松地在树上行走:How to: Implement an Expression Tree Visitor