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

标签 c#

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

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

answer = str.magic(); 

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

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

最佳答案

您可以使用 CodeDom 获得“ native ”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;
}

关于c# - 如何将我的字符串作为代码执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34758802/

相关文章:

c# - 使用阻止在 VB.NET 中编译的自定义文本创建错误(C# 中的#error)

c# - BeginForm 弄乱了 .NET 6 中的 Controller 路径值

C# 线程,如何让线程运行带有参数的方法?

c# - 如何使用 C# 读取和写入硬件寄存器?

c# - DataAdapter.Fill(数据集)

c# - WebBrowser 控件中的嵌入式 iframe 未加载

c# - 一个进程中加载​​的最大应用域数

c# - 执行 javascript 时,Watin 集成测试因 System.UnauthorizedAccessException 而失败

c# - 在运行时动态调用 Web 服务

C# JSON 反序列化 : Type is an interface or abstract class and cannot be instantiated