In C# is there an eval function?

寵の児 提交于 2019-11-28 06:37:22

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"));

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");
...

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();
    }
}

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!