C# .NET 中是否有字符串数学计算器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/355062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a string math evaluator in .NET?
提问by Guy
If I have a string with a valid math expression such as:
如果我有一个带有有效数学表达式的字符串,例如:
String s = "1 + 2 * 7";
Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15.
.NET 中是否有内置库/函数可以为我解析和评估该表达式并返回结果?在这种情况下 15。
采纳答案by user21826
You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.)
您可以添加对 Microsoft 脚本控制库 (COM) 的引用并使用这样的代码来计算表达式。(也适用于 JScript。)
Dim sc As New MSScriptControl.ScriptControl()
sc.Language = "VBScript"
Dim expression As String = "1 + 2 * 7"
Dim result As Double = sc.Eval(expression)
Edit- C# version.
编辑- C# 版本。
MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
sc.Language = "VBScript";
string expression = "1 + 2 * 7";
object result = sc.Eval(expression);
MessageBox.Show(result.ToString());
Edit- The ScriptControl is a COM object. In the "Add reference" dialog of the project select the "COM" tab and scroll down to "Microsoft Script Control 1.0" and select ok.
编辑- ScriptControl 是一个 COM 对象。在项目的“添加引用”对话框中,选择“COM”选项卡并向下滚动到“Microsoft Script Control 1.0”并选择“确定”。
回答by Guy
For anybody developing in C# on Silverlight here's a pretty neat trick that I've just discovered that allows evaluation of an expression by calling out to the Javascript engine:
对于在 Silverlight 上用 C# 开发的任何人来说,这里有一个非常巧妙的技巧,我刚刚发现它允许通过调用 Javascript 引擎来评估表达式:
double result = (double) HtmlPage.Window.Eval("15 + 35");
回答by cbp
Actually there is kind of a built in one - you can use the XPath namespace! Although it requires that you reformat the string to confirm with XPath notation. I've used a method like this to handle simple expressions:
实际上有一种内置的 - 您可以使用 XPath 命名空间!尽管它要求您重新格式化字符串以使用 XPath 表示法进行确认。我使用过这样的方法来处理简单的表达式:
public static double Evaluate(string expression)
{
var xsltExpression =
string.Format("number({0})",
new Regex(@"([\+\-\*])").Replace(expression, " ")
.Replace("/", " div ")
.Replace("%", " mod "));
return (double)new XPathDocument
(new StringReader("<r/>"))
.CreateNavigator()
.Evaluate(xsltExpression);
}
回答by GreyCloud
Have you seen http://ncalc.codeplex.com?
你见过http://ncalc.codeplex.com吗?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
它是可扩展的、快速的(例如,有自己的缓存)使您能够通过处理 EvaluateFunction/EvaluateParameter 事件在运行时提供自定义函数和变量。它可以解析的示例表达式:
Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");
e.Parameters["Pi2"] = new Expression("Pi * Pi");
e.Parameters["X"] = 10;
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "Pi")
args.Result = 3.14;
};
Debug.Assert(117.07 == e.Evaluate());
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.
它还本机处理 unicode 和许多数据类型。如果您想更改语法,它会附带一个鹿角文件。还有一个 fork 支持 MEF 加载新功能。
回答by ma81xx
If you need very simple thing you can use the DataTable
:-)
如果你需要非常简单的东西,你可以使用DataTable
:-)
Dim dt As New DataTable
dt.Columns.Add("A", GetType(Integer))
dt.Columns.Add("B", GetType(Integer))
dt.Columns.Add("C", GetType(Integer))
dt.Rows.Add(New Object() {12, 13, DBNull.Value})
Dim boolResult As Boolean = dt.Select("A>B-2").Length > 0
dt.Columns.Add("result", GetType(Integer), "A+B*2+ISNULL(C,0)")
Dim valResult As Object = dt.Rows(0)("result")
回答by user2069333
namespace CalcExp
{
internal class Program
{
private static void Main(string[] args)
{
double res = Evaluate("4+5/2-1");
Console.WriteLine(res);
}
public static double Evaluate(string expression)
{
var xsltExpression =
string.Format("number({0})",
new Regex(@"([\+\-\*])").Replace(expression, " ")
.Replace("/", " div ")
.Replace("%", " mod "));
// ReSharper disable PossibleNullReferenceException
return (double)new XPathDocument
(new StringReader("<r/>"))
.CreateNavigator()
.Evaluate(xsltExpression);
// ReSharper restore PossibleNullReferenceException
}
}
}
回答by Tim Schmelter
Strange that this famous and old question has not an answer that suggests the builtin DataTable.Compute
-"trick". Here it is.
奇怪的是,这个著名而古老的问题没有一个暗示内置DataTable.Compute
“技巧”的答案。这里是。
double result = Convert.ToDouble(new DataTable().Compute("1 + 2 * 7", null));
The following arithmetic operators are supported in expressions:
表达式支持以下算术运算符:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
More informations: DataColumn.Expression
at Expression Syntax.
更多信息:DataColumn.Expression
在表达式语法。
回答by MuSTaNG
I would also have a look at Jace (https://github.com/pieterderycke/Jace). Jace is a high performance math parser and calculation engine that supports all the .NET flavors (.NET 4.x, Windows Phone, Windows Store, ...). Jace is also available through NuGet: https://www.nuget.org/packages/Jace
我也会看看 Jace ( https://github.com/pieterderycke/Jace)。Jace 是一种高性能数学解析器和计算引擎,支持所有 .NET 风格(.NET 4.x、Windows Phone、Windows Store 等)。Jace 也可通过 NuGet 获得:https: //www.nuget.org/packages/Jace
回答by Rushui Guan
I implemented an expression parser a few years ago and had published a version of it in GitHuband Nuget:Albatross.Expressionrecently. It contains a ExecutionContext class that can evaluate a set of expressions such as:
几年前我实现了一个表达式解析器,最近在GitHub和Nuget:Albatross.Expression上发布了它的一个版本。它包含一个 ExecutionContext 类,可以计算一组表达式,例如:
- MV = Price * Qty;
- Price = (Bid + Ask)/2;
- Bid = .6;
- Ask = .8;
- MV = 价格 * 数量;
- 价格=(买价+卖价)/2;
- 出价 = .6;
- 问= .8;
It also has built in circular reference check which is useful to avoid a stack overflow.
它还内置了循环引用检查,这有助于避免堆栈溢出。
回答by ISCI
Flee Fast Lightweight Expression Evaluator
Flee 快速轻量级表达式评估器
Language Reference
语言参考
- ArithmeticOperators Example: a*2 + b ^ 2 - 100 % 5
- ComparisonOperators Example: a <> 100
- AndOrXorNotOperators Example (logical): a > 100 And Not b = 100
- ShiftOperators Example: 100 >> 2
- Concatenation Example: "abc" + "def"
- Indexing Example: arr[i + 1] + 100
- Literals
- Casting Example: 100 + cast(obj, int)
- ConditionalOperator Example: If(a > 100 and b > 10, "both greater", "less")
- InOperator Example (List): If(100 in (100, 200, 300, -1), "in", "not in")
- Overloaded Operators On Types
- 算术运算符示例:a*2 + b ^ 2 - 100 % 5
- 比较运算符示例:a <> 100
- AndOrXorNotOperators 示例(逻辑):a > 100 And Not b = 100
- ShiftOperators 示例:100 >> 2
- 连接示例:“abc”+“def”
- 索引示例:arr[i + 1] + 100
- 文字
- 铸造示例:100 + cast(obj, int)
- ConditionalOperator 示例:If(a > 100 and b > 10, "both Greater", "less")
- InOperator 示例(列表):If(100 in (100, 200, 300, -1), "in", "not in")
- 类型上的重载运算符
Example :
例子 :
Imports Ciloci.Flee
Imports Ciloci.Flee.CalcEngine
Imports System.Math
Dim ec As New Ciloci.Flee.ExpressionContext
Dim ex As IDynamicExpression
ec.Imports.AddType(GetType(Math))
ec.Variables("a") = 10
ec.Variables("b") = 40
ex = ec.CompileDynamic("a+b")
Dim evalData
evalData = ex.Evaluate()
Console.WriteLine(evalData)
The output : 50
输出:50