如何将我的字符串作为代码执行

时间:2016-01-13 05:09:59

标签: c#

我目前正在制作计算器。我知道如何编写逻辑,但我很好奇是否可以按照我要解释的方式完成。

for i, f in enumerate(foo):

    # Create the RadioSelect widget
    chk = Pmw.RadioSelect(parent,
            buttontype='checkbutton',
            command=self.checkbutton_callback)

    # Add a numbered checkbutton
    chk.add(str(i))

    # Place it on the grid
    chk.grid(row=i, column=0)

    # Without the following code, it works fine, but all the buttons are enabled
    # With it, the program chokes on the `configure()` call
    if not f.active:
        print "This gets printed."
        chk.configure(checkbutton_state='disabled')
        print "But this doesn't."

现在我想要的是如何将str转换为可执行代码。

2 个答案:

答案 0 :(得分:4)

您可以使用CodeDom来获取“本机”C#解析器。 (您应该改进错误处理。)

using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

...

static void Main()
{
    double? result = Calculate("12 + 43 * (12 / 2)");
}

static double? Calculate(string formula)
{
    double result;
    try
    {
        CompilerParameters compilerParameters = new CompilerParameters
        {
            GenerateInMemory = true, 
            TreatWarningsAsErrors = false, 
            GenerateExecutable = false, 
        };

        string[] referencedAssemblies = { "System.dll" };
        compilerParameters.ReferencedAssemblies.AddRange(referencedAssemblies);

        const string codeTemplate = "using System;public class Dynamic {{static public double Calculate(){{return {0};}}}}";
        string code = string.Format(codeTemplate, formula);

        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerResults compilerResults = provider.CompileAssemblyFromSource(compilerParameters, new string[]{code});
        if (compilerResults.Errors.HasErrors)
            throw new Exception();

        Module module = compilerResults.CompiledAssembly.GetModules()[0];
        Type type = module.GetType("Dynamic");
        MethodInfo method = type.GetMethod("Calculate");

        result = (double)(method.Invoke(null, null));
    }
    catch (Exception)
    {
        return null;
    }

    return result;
}

答案 1 :(得分:1)

您可以使用NCalc库Click here获取更多信息。 您可以从here

下载该dll文件

示例:

NCalc.Expression exp= new NCalc.Expression("(12*3)-29");
object obj = exp.Evaluate();
MessageBox.Show(obj.ToString());