动态计算字符串表达式的结果

7

有没有一种方法可以动态计算字符串表达式的结果,例如mystring = "2*a+32-Math.Sin(6)",并且知道a是我拥有的一个变量,也许有一些动态解决方案或使用System.Reflection

string mystring = "2*a+32-Math.Sin(6)"`;
decimal result = SomeMethod(mystring,3); // where a = 3 for example
6个回答

19

让 JavaScript 来计算你的表达式怎么样?

Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));

dynamic obj = Activator.CreateInstance(scriptType, false);
obj.Language = "javascript";

var res = obj.Eval("a=3; 2*a+32-Math.sin(6)");

那是什么 GUID,有没有避免的方法? - S3ddi9
我们能否在.NET和MSScript COM之间使用Interop?而不需要GUID。 - S3ddi9
我将添加翻译的文本作为参考,这会更好。 - S3ddi9
1
@SéddikLaraba 引用 COM 对象或使用 CLSID 创建对象都是相等的。使用任何你想要的方法。 - L.B
1
我已经将 msscript.ocx 添加到我的引用中,它运行得非常好,谢谢!! - S3ddi9
显示剩余3条评论

5

您可以在以下方式中的SomeMethod中使用Datatable的Compute方法:

       static decimal Somemethod(int val)
        {
            var result = (decimal)new DataTable().Compute(string.Format("2*{0}+32-{1}", val, Math.Sin(6)), "");
            return result;
        }

简单来说,您可以像这样调用:

        result = Somemethod(3);

5

如果发现这个,它完美地工作了,抱歉打扰了,我想要的只是即时编译器。& 这就是我得到的。

MessageBox.Show(Eval("5*3-Math.Sin(12) + 25*Math.Pow(3,2)").ToString());

public static object Eval(string sCSCode)
    {

        CodeDomProvider icc = CodeDomProvider.CreateProvider("C#");
        CompilerParameters cp = new CompilerParameters();

        cp.ReferencedAssemblies.Add("system.dll");
        cp.ReferencedAssemblies.Add("system.xml.dll");
        cp.ReferencedAssemblies.Add("system.data.dll");
        cp.ReferencedAssemblies.Add("system.windows.forms.dll");
        cp.ReferencedAssemblies.Add("system.drawing.dll");

        cp.CompilerOptions = "/t:library";
        cp.GenerateInMemory = true;

        StringBuilder sb = new StringBuilder("");
        sb.Append("using System;\n");
        sb.Append("using System.Xml;\n");
        sb.Append("using System.Data;\n");
        sb.Append("using System.Data.SqlClient;\n");
        sb.Append("using System.Windows.Forms;\n");
        sb.Append("using System.Drawing;\n");

        sb.Append("namespace CSCodeEvaler{ \n");
        sb.Append("public class CSCodeEvaler{ \n");
        sb.Append("public object EvalCode(){\n");
        sb.Append("return " + sCSCode + "; \n");
        sb.Append("} \n");
        sb.Append("} \n");
        sb.Append("}\n");

        CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
        if (cr.Errors.Count > 0)
        {
            MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText,
               "Error evaluating cs code", MessageBoxButton.OK,
               MessageBoxImage.Error);
            return null;
        }

        System.Reflection.Assembly a = cr.CompiledAssembly;
        object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");

        Type t = o.GetType();
        System.Reflection.MethodInfo mi = t.GetMethod("EvalCode");

        object s = mi.Invoke(o, null);
        return s;

    }

你想在每次sCSCode更改时创建一个新的程序集(它将在内部使用csc)吗?只需创建一个循环并查看性能即可。 - L.B
这很糟糕吗?因为我想尽可能使用 .Net 内部方法,如果太昂贵,我会采用 JavaScript 解决方案。 - S3ddi9
具有实例的对象 o 可以存储以获得更好的性能,并在稍后调用。 - nio

3

以下是我所知道的一些在C#中动态评估字符串表达式的流行方法。

微软解决方案

非微软解决方案(并不是说这有什么问题)


2

我认为没有原生支持你所要求的内容,但有许多方法可以实现它,其中没有一种是完全平凡的,但我认为它们的难度顺序如下:


1

创建抽象类,其中包含您想要用于评估表达式的方法。在运行时创建一个继承该抽象类的新类。我很快会分享代码。

如承诺所述,这是实现它的代码:

    public class BaseClass
    {
    public BaseClass(){}
    public virtual double Eval(double x,double y){return 0;}
}
public class MathExpressionParser
{
    private BaseClass Evalulator=null;
    public MathExpressionParser(){}
    public bool Intialize(string equation)
    {
        Microsoft.CSharp.CSharpCodeProvider cp=new Microsoft.CSharp.CSharpCodeProvider();
        System.CodeDom.Compiler.ICodeCompiler comp=cp.CreateCompiler();
        System.CodeDom.Compiler.CompilerParameters cpar=new CompilerParameters();

        cpar.GenerateInMemory=true;
        cpar.GenerateExecutable=false;
        cpar.ReferencedAssemblies.Add("system.dll");
        cpar.ReferencedAssemblies.Add("EquationsParser.exe");   //Did you see this before;

        string sourceCode="using System;"+
                          "class DrivedEval:EquationsParser.BaseClass" +
                          "{"+   
                                  "public DrivedEval(){}"+
                                  "public override double Eval(double x,double y)"+
                                  "{"+
                                        "return "+ /*Looook here code insertion*/ equation +";"+
                                  "}"+
                          "}";
        //the previouse source code will be compiled now(run time);
        CompilerResults result=comp.CompileAssemblyFromSource(cpar,sourceCode);

        //If there are error in the code display it for the programmer who enter the equation
        string errors="";
        foreach(CompilerError rrr in result.Errors)
        {
            if(rrr.IsWarning)
                continue;
            errors+="\n"+rrr.ErrorText;
            errors+="\n"+rrr.ToString();
        }
        //You Can show error if there in the sourceCode you just compiled uncomment the following
        //MessageBox.Show(errors);
        if(result.Errors.Count==0&&result.CompiledAssembly!=null)
        {
            Type objtype=result.CompiledAssembly.GetType("DrivedEval");
            try
            {
                if(objtype!=null)
                {
                    Evalulator=(BaseClass)Activator.CreateInstance(objtype);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message,"Error in Creation the object");
            }
            return true;
        }
        else return false;
    }
    public double evaluate(double x,double y)
    {
        if(Evalulator==null)
            return 0.0;
        return this.Evalulator.Eval(x,y);
    }
}

你需要进行以下简单的测试以确保它能正常工作:

private void button1_Click(object sender, System.EventArgs e)
{

    if(parser.Intialize(textBox1.Text)==false)
{
    MessageBox.Show("Check equation");
    return;
}
textBox4.Text=(parser.evaluate(double.Parse(textBox2.Text),double.Parse(textBox3.Text))).ToString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接