DataTable.Computeメソッドを使用して、限定された(つまり単純な)数式のショートカットがあります。明らかに、これは堅牢ではなく(機能が制限されている)、この目的でDataTableを悪用するのはハックだと感じますが、現在の回答に追加すると思いました。
例:
var result = new DataTable().Compute("3+(7/3.5)", null); // 5
「Sin(90)」はこのアプローチでは機能しません。サポートされている関数のリストについては、特に「集計」セクションの下にあるDataColumn.Expressionプロパティページを参照してください。
System.CodeDom名前空間の使用はオプションです。
いくつかの役立つリンク:
編集:あなたのコメントに対処するために、三角関数を同等の数学クラスのメソッドに置き換えることを示すアプローチがあります。
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」グループの内容を知っておく必要があることに注意してください。私はそれらがintであることを知っているので、それらにInt32.Parseを使用しました。それらがアイテムの組み合わせである場合、この単純なアプローチは機能しません。サポートされていない関数呼び出しで複雑になりすぎた場合は、ソリューションを常にバンドエイドする必要があると思います。その場合は、CodeDomアプローチなどの方が適している可能性があります。