【问题标题】:How to execute my string as code如何将我的字符串作为代码执行
【发布时间】:2016-01-13 05:09:59
【问题描述】:

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

String str = "12 + 43 * (12 / 2)";
int answer;

answer = str.magic(); 

//str.magic is the same as 
answer =   12 + 43 * (12 / 2);

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

【问题讨论】:

标签: c#


【解决方案1】:

您可以使用 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;
}

【讨论】:

  • 注意:这在 .net core 或 .net5+ 中不起作用。为此我推荐this
【解决方案2】:

您可以简单地使用 NCalc 库 Click here 获取更多信息。 你可以从here下载那个dll文件

示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-07
    • 2021-12-30
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多