如何在C#/.net中评估数学表达式 [英] How to evaluate mathematical expressions in c# / .net
问题描述
可能重复:
使用C#将字符串表达式转换为Integer Value >
我只是想知道C#/.NET中是否有任何内置函数,以便在运行时解析和评估数学表达式.
I'm just wondering if there are any built-in functions in C# / .NET in order to parse and evaluate mathematical expressions at run-time.
我们的用户应该能够将表达式写到文本文件中,例如
Our users should be able to write expressions into a text file, like
bmi = weight / (height * height)
然后程序应该能够计算这些公式
and the program should then be able to calculate these formulas
对于我们的表达式,我们至少需要以下功能:
For our expressions, we need at least these capabilities:
- 基本算术运算+-*/
- 托架
- 用于计算平方根和自然对数的函数,例如sqrt(),ln()
- 使用预定义变量.变量将由我们的程序填充,然后用户应该能够使用它们进行计算.
如果.NET中没有这样的东西,那么您可以推荐一个库吗?
If there is no such thing in .NET, is there a library you could recommend?
好吧,我自己可以编写一个表达式解析器-我知道所有的理论,这甚至是大学里最伟大的事情之一:-)-但是,这仍然感觉像是在重新发明轮子
Well, I would be able to write an expression parser myself - I know all the theory about it, this was even one of the greatest things at university :-) - but still, it just feels like re-inventing the wheel.
推荐答案
The closest you can get within the BCL is the Expression
class, though it will have no parsing capabilities.
There is a bunch of third party of mathematical expression parsers for .NET, so you don't need to reinvent the wheel.
这篇关于如何在C#/.net中评估数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!