问题
I am just curious. Like in interpreted languages or even statement calculators how do people convert the strings given by input or files to actual expressions? e.g "Enter Calculation: " and you write "2*7/4" which is a string. How does the program convert the string into an actual expression? It is easy to convert a string to an int but how do you convert operators like + , - , /, etc.? I understand that these kind of things are usually implemented in C/C++ but is it possible to make such a thing in a high-level language like C#? And If yes then how?
回答1:
Here's an article you might check out. There are also tools like Flee. Or yet another technique which allows you to evaluate C# expressions using a CodeDom provider.
回答2:
I believe this can be achieved using expression trees, which is how LINQ is implemented.
http://msdn.microsoft.com/en-us/library/bb397951.aspx
回答3:
Google "parse tree". One can be written in any Turing-complete language.
来源:https://stackoverflow.com/questions/6516806/how-would-you-create-an-expression-parser-in-c