dynamicexpresso / DynamicExpresso

C# expressions interpreter
http://dynamic-expresso.azurewebsites.net/
MIT License
1.91k stars 364 forks source link

Parameter name does not support operators #301

Closed dzp0839 closed 1 month ago

dzp0839 commented 5 months ago

Is there any way to handle situations where parameter names contain operators?

var interpreter = new Interpreter();
var parameters = new[]
{
    new Parameter("name-y", 24),
    new Parameter("y", 10)
};
var result = interpreter.Eval<double>("name-y / (y + 2)", parameters);

This code cannot obtain the correct result.

davideicardi commented 5 months ago

I think this is not supported and it is out of scope for the project. We try to follow the same rules of C#, where name-y is not a valid identifier. Maybe you can preprocess the expression and replace the invalid identifier with something valid? Like name-y to name_y?

dzp0839 commented 5 months ago

Thank you for your suggestion. Actually, due to my usage scenario, I need to perform calculations based on parameters, like this

  var interpreter = new Interpreter();
  var formula = "P1-X * (P2-Y + P3-Z)";
  var parameters = new[]
  {
      new Parameter("P1-X", 24),
      new Parameter("P2-Y", 10),
      new Parameter("P3-Z", 10)
  };
  var result = interpreter.Eval<double>(formula, parameters);

In the end, I chose to wrap my parameters in {} and replace them with the corresponding data to implement it

var interpreter = new Interpreter();
var formula = "{P1-X} * ({P2-Y} + {P3-Z})"; 
var result = interpreter.Eval<double>(ConvertHelper(formula)); //"24 * (10 + 10)"