C# - 将字符串(包含方法或函数)转换为C#中的实际函数或方法

时间:2015-06-20 04:15:32

标签: c# string methods

我有一个字符串。例如

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

我想评估或创建函数,比如func(int a,int b),其代码为'str'。

2 个答案:

答案 0 :(得分: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));
    }
}

答案 1 :(得分:1)

一般来说,这不是一件容易的事情,但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#中的动态代码生成并不容易,这只是一个开始。