要扩展我的评论,通常您需要:
- 解析您的输入并将其转换为标记,其中标记只是转换为 C# 对象的字符串的语义组件。
如果我们使用该示例(A+B)*C
,标记将是对象“括号(打开),变量(A),运算符(+),变量B,括号(关闭),运算符(*),变量(C)”。
我不会详细介绍如何执行此操作,因为这不是问题的一部分,但我曾经使用正则表达式序列编写了一个非常简单但功能强大的标记器,因为它们已经完成了解析所需的大部分艰苦工作。
- 考虑运算符优先级规则和括号,重新排序您的令牌,就像它们需要处理一样。这可以通过使用 Dijkstra 的调车码算法来完成,请参阅https://en.wikipedia.org/wiki/Shunting-yard_algorithm示例。
您重新排序的令牌现在是“变量 (A)、变量 (B)、运算符 (+)、变量 (C)、变量 (*)。
- 将您的令牌树或队列(无论您选择如何存储它)转换为表达式树。
如果是令牌队列,最后一步是:
// for demo purposes I manually fill the list of tokens
// with the tokens in order how they are output by the shunting-yard algorithm
var tokenQueue = new Token[]
{
new VariableToken("A"),
new VariableToken("B"),
new OperatorToken("+"),
new VariableToken("C"),
new OperatorToken("*")
};
var inputParameter = Expression.Parameter(typeof(TableTest));
var expressions = new Stack<Expression>();
foreach (var token in tokenQueue)
{
// transform token to expression by using the helper methods of https://msdn.microsoft.com/de-de/library/system.linq.expressions.expression_methods(v=vs.110).aspx
switch (token)
{
case VariableToken variableToken:
// this will reference the property in your TableTest input specified by the variable name, e.g. "A" will reference TableTest.A
expressions.Push(Expression.Property(inputParameter, variableToken.Name));
break;
case OperatorToken operatorToken:
// This will take two expression from the stack, give these to input to an operator and put the result back onto the queue for use for the next operator
var rightOperand = expressions.Pop();
var leftOperand = expressions.Pop();
if (operatorToken.Name == "+")
{
expressions.Push(Expression.Add(leftOperand, rightOperand));
}
else if (operatorToken.Name == "*")
{
expressions.Push(Expression.Multiply(leftOperand, rightOperand));
}
break;
}
}
// create and fill output model with final expression
var outputModelExpr = Expression.New(typeof(OutputModel).GetConstructor(new[] {typeof(decimal) }), expressions.Single());
// create the lambda expression
// in this example it will have the form: x => return new OutputModel((x.A + x.B) * x.C)
Expression<Func<TableTest, OutputModel>> lambda = Expression.Lambda<Func<TableTest, OutputModel>>(outputModelExpr, inputParameter);
// only for testing purposes: compile it to a function and run it
var calc = lambda.Compile();
var testInput = new TableTest { A = 1, B = 2, C = 3 };
Console.WriteLine(calc(testInput).Result); // returns 9, because (A + B) * C = (1 + 2) * 3 = 9
使用令牌类:
public abstract class Token
{
public string Name { get; protected set; }
}
public class VariableToken : Token
{
public VariableToken(string name) { Name = name; }
}
public class OperatorToken : Token
{
public OperatorToken(string name) { Name = name; }
}
请注意,我向 OutputModel 添加了一个构造函数,因为这使表达式更容易:
public class OutputModel
{
public OutputModel(decimal result) { Result = result; }
public decimal Result {get;set;}
}