首页 > Windows开发 > 详细

c#动态编译并执行字符串

时间:2017-01-19 16:08:04      阅读:242      评论:0      收藏:0      [点我收藏+]

比较简单,步骤是这样的

string -> compiler -> assembly -> reflection -> execution

直接上代码:

using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
 
class Program
{
    public static void Main()
    {
        // The C# code to execute
        string code = "using System; " +
                      "using System.IO; " +
                      "public class MyClass{ " +
                      "   public static void PrintConsole(string message){ " +
                      "       Console.WriteLine(message); " +
                      "   } " +
                      "} ";
 
        // Compiler and CompilerParameters
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        CompilerParameters compParameters = new CompilerParameters();
 
        // Compile the code
        CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code);
 
        // Create a new instance of the class ‘MyClass‘
        object myClass = res.CompiledAssembly.CreateInstance("MyClass");
 
        // Call the method ‘PrintConsole‘ with the parameter ‘Hello World‘
        // "Hello World" will be written in console
        myClass.GetType().GetMethod("PrintConsole").Invoke(myClass, new object[] {"Hello World" });
 
        Console.Read();
    }
}

  

c#动态编译并执行字符串

原文:http://www.cnblogs.com/y114113/p/6306994.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!