如何在 C# 中创建表达式解析器?
我只是好奇。就像在解释语言甚至语句计算器中一样,人们如何将输入或文件给出的字符串转换为实际表达式?例如“输入计算:”,然后写入“2*7/4”,这是一个字符串。程序如何将字符串转换为实际的表达式?将字符串转换为 int 很容易,但是如何转换运算符,例如 + 、 - 、 / , ETC。?我知道这些东西通常是用C/C++实现的,但是有可能用C#这样的高级语言来实现这样的东西吗?如果是的话怎么办?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以查看以下一篇文章。还有诸如 Flee 之类的工具。或者还有另一种技术,它允许您使用 CodeDom 提供程序评估 C# 表达式。
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.
我相信这可以使用表达式树来实现,这就是 LINQ 的实现方式。
http://msdn.microsoft.com/en-us/library/bb397951.aspx
I believe this can be achieved using expression trees, which is how LINQ is implemented.
http://msdn.microsoft.com/en-us/library/bb397951.aspx
谷歌“解析树”。可以用任何图灵完备的语言来编写。
Google "parse tree". One can be written in any Turing-complete language.