【问题标题】:C# - Convert a string (which contains method or function) to an actual function or method in C#C# - 将字符串(包含方法或函数)转换为 C# 中的实际函数或方法
【发布时间】:2015-06-20 04:15:31
【问题描述】:

我有一个字符串。例如

 string str="if(a>b) {return a;} else {return b;}"

我想评估或制作函数,比如 func(int a, int b),它的代码为 'str'。

【问题讨论】:

  • 你给出的例子,是最简单的场景还是最复杂的场景?如果是前者,那么您不妨向 Microsoft 发送一封电子邮件,要求他们与您分享他们的编译器代码 :)。编写解析器/编译器并非易事,我通常不会问“为什么”,但您为什么要考虑实现此功能? :)
  • @Ruskin...我问这个是因为我想使用用户输入的“if else”作为程序本身的功能。

标签: c# string methods


【解决方案1】:

您可能需要使用CSharpCodeProvider,如this 回答

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

【讨论】:

    【解决方案2】:

    一般来说,这不是一件容易的事,但 System.CodeDom 命名空间是您旅程的起点。

    请看下面关于此事的 CodeProject 文章作为开始:http://www.codeproject.com/Articles/26312/Dynamic-Code-Integration-with-CodeDom

    它的基本原理如下(摘自codeproject文章):

    private static Assembly CompileSource( string sourceCode )
    {
       CodeDomProvider cpd = new CSharpCodeProvider();
       CompilerParameters cp = new CompilerParameters();
       cp.ReferencedAssemblies.Add("System.dll");
       //cp.ReferencedAssemblies.Add("ClassLibrary1.dll");
       cp.GenerateExecutable = false;
       // Invoke compilation.
       CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);
    
       return cr.CompiledAssembly;
    }
    

    生成的程序集将包含您感兴趣的类/方法/代码,然后您可以使用反射来调用您的方法。由于您的示例只使用了一个代码片段,因此您可能必须先将其包装在一个类/方法中,然后再将其传递给此方法。

    希望对您有所帮助,但 C# 中的动态代码生成并不容易,这只是一个开始。

    【讨论】:

    • 我收到消息,mscorlib.dll 中出现“System.IO.FileNotFoundException”类型的未处理异常附加信息:无法加载文件或程序集“file:///C:\Users\ Sabhrish\AppData\Local\Temp\5diuzimc.dll' 或其依赖项之一。系统找不到指定的文件。
    猜你喜欢
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2015-09-22
    相关资源
    最近更新 更多