Evaluation using dynamic variables

This method uses a predefined expression owner that allows you to define variables dynamically instead of using hard-coded fields.

// Use the DynamicExpressionOwner so we can use variables
DynamicExpressionOwner owner = new DynamicExpressionOwner();
// Define variables "a" and "b" and specify their type
owner.DefineVariable("a", typeof(int));
owner.DefineVariable("b", typeof(double));

// Set the values of the variables
owner.SetVariableValue("a", 2);
owner.SetVariableValue("b", 16.0);

// Create an expression that uses the variables
Expression e = new Expression("a ^ b", owner);            
ExpressionEvaluator<double> evaluator = (ExpressionEvaluator<double>) e.Evaluator;
// Evaluate the expression and get the result
double result = evaluator();

// Change the values of the variables
owner.SetVariableValue("a", 4);
owner.SetVariableValue("b", 3.4);

// Re-evaluate to get the updated result
result = evaluator();

Last edited Sep 23, 2007 at 6:50 PM by ECiloci, version 1

Comments

No comments yet.