I'm typing an equation into a textbox
that will generate the graph of the given parabola. Is it possible to use an eval function? My C# 2010 doesn't have microsoft.jscript
.
问题:
回答1:
C# doesn't have a comparable Eval function but creating one is really easy:
public static double Evaluate(string expression)
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("expression", string.Empty.GetType(), expression);
System.Data.DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
Now simply call it like this:
Console.WriteLine(Evaluate("9 + 5"));
回答2:
You can easily do this with the "Compute" method of the DataTable class.
static Double Eval(String expression)
{
System.Data.DataTable table = new System.Data.DataTable();
return Convert.ToDouble(table.Compute(expression, String.Empty));
}
Pass a term in form of a string to the function in order to get the result.
Double result = Eval("7 * 6");
result = Eval("17 + 4");
...
回答3:
You can create one yourself by using CodeDom. It will be slow because it creates a new assembly every time you call Eval.
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(ExpressionEvaluator.Eval("(2 + 2) * 2"));
}
}
public class ExpressionEvaluator
{
public static double Eval(string expression)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerResults results =
codeProvider
.CompileAssemblyFromSource(new CompilerParameters(), new string[]
{
string.Format(@"
namespace MyAssembly
{{
public class Evaluator
{{
public double Eval()
{{
return {0};
}}
}}
}}
",expression)
});
Assembly assembly = results.CompiledAssembly;
dynamic evaluator =
Activator.CreateInstance(assembly.GetType("MyAssembly.Evaluator"));
return evaluator.Eval();
}
}
回答4:
It's possible using the System.Reflection.Emit or System.CodeDom namespaces, but it's not exactly a good idea as there's no mechanism to control what namespaces are and are not allowed to be used. You write an eval() expecting simple expressions, and the next thing you know a user is suing you because your code allowed them to enter a string that wiped their hard drive. eval()
-like functions are huge gaping security holes and should be avoided.
The preferred alternative in the .Net world is a DSL (domain specific language). If you google around, you can find some pre-created DSL's for common tasks such as arithmetic.
回答5:
There is no native C# eval function; but as others have previously stated, there are several workarounds for what you are trying to do.
If you're interested in evaluating more complicated C# code, my C# eval program provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, http://csharp-eval.com, for additional details.