通过使用有限(即简单)数学表达式有一个捷径DataTable.Compute方法 http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx。显然,这并不健壮(功能有限),并且出于此目的滥用 DataTable 感觉很黑客,但我想我会添加到当前的答案中。
Example:
var result = new DataTable().Compute("3+(7/3.5)", null); // 5
“Sin(90)”不适用于这种方法。请参阅DataColumn.Expression 属性页 http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx有关受支持函数的列表,特别是在“聚合”部分下。
使用 System.CodeDom 命名空间是一种选择。
一些有用的链接:
- CodeDom 计算器 http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
- 使用 CodeDom 评估数学表达式 http://www.vbforums.com/showthread.php?t=397264
- 相关SO问题:.NET 中有字符串数学计算器吗? https://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net
EDIT:为了解决您的评论,这里有一种方法来演示用等效的数学类方法替换三角函数。
C#
string expression = "(Sin(0) + Cos(0)+Tan(0)) * 10";
string updatedExpression = Regex.Replace(expression, @"(?<func>Sin|Cos|Tan)\((?<arg>.*?)\)", match =>
match.Groups["func"].Value == "Sin" ? Math.Sin(Int32.Parse(match.Groups["arg"].Value)).ToString() :
match.Groups["func"].Value == "Cos" ? Math.Cos(Int32.Parse(match.Groups["arg"].Value)).ToString() :
Math.Tan(Int32.Parse(match.Groups["arg"].Value)).ToString()
);
var result = new DataTable().Compute(updatedExpression, null); // 10
VB.NET
Dim expression As String = "(Sin(0) + Cos(0)+Tan(0)) * 10"
Dim updatedExpression As String = Regex.Replace(expression, "(?<func>Sin|Cos|Tan)\((?<arg>.*?)\)", Function(match As Match) _
If(match.Groups("func").Value = "Sin", Math.Sin(Int32.Parse(match.Groups("arg").Value)).ToString(), _
If(match.Groups("func").Value = "Cos", Math.Cos(Int32.Parse(match.Groups("arg").Value)).ToString(), _
Math.Tan(Int32.Parse(match.Groups("arg").Value)).ToString())) _
)
Dim result = New DataTable().Compute(updatedExpression, Nothing)
但请注意,您需要知道“arg”组的内容。我知道它们是整数,所以我对它们使用了 Int32.Parse 。如果它们是项目的组合,那么这种简单的方法将不起作用。我怀疑如果解决方案因更多不受支持的函数调用而变得过于复杂,您将不断需要对解决方案进行创可贴,在这种情况下,CodeDom 方法或其他方法可能更合适。