动态编译并执行字符串

动态编译并执行字符串

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

class Program
{
    public static void Main()
    {
        // 要执行的C#代码
        string code = "using System; " +
                      "using System.IO; " +
                      "public class MyClass{ " +
                      "   public static void PrintConsole(string message){ " +
                      "       Console.WriteLine(message);" +
                      "   } " +
                      "} ";

        //编译器和编译器参数
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        CompilerParameters compParameters = new CompilerParameters();

        //编译代码
        CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code);

        // 创建类“MyClass”的新实例    
        // 有命名空间的,需要命名空间.类名
        object myClass = res.CompiledAssembly.CreateInstance("MyClass");

        //使用参数“Hello World”调用方法“PrintConsole”
        //“Hello World”将在控制台中编写
        myClass.GetType().GetMethod("PrintConsole").Invoke(myClass, new object[] { "Hello World" });

        Console.Read();
    }
}
posted @ 2021-10-07 00:15  镜子-眼泪  阅读(67)  评论(0)    收藏  举报