美文网首页
动态编译基础

动态编译基础

作者: forsek | 来源:发表于2017-10-19 13:43 被阅读0次
    一. 将函数或方法放在文本文件或dll文件或字符串中,可以修改添加后,直接使用主程序调用改变后的功能。(把方法和主程序分离,方便修改与添加)
    using System;
    using Microsoft.CSharp;
    using System.CodeDom.Compiler;
    
    class Program
    {
        public static void Main()
        {
            // The C# code to execute,分离出的方法,字符串形式,方法名PrintConsole,参数message,功能:打印message信息
            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',调用PrintConsole方法,使用"Hello World"参数。
            // "Hello World" will be written in console
            myClass.GetType().GetMethod("PrintConsole").Invoke(myClass, new object[] { "Hello World" });
    
            Console.Read();
    

    [原文链接](http://www.jb51.net/article/117946.htm

    相关文章

      网友评论

          本文标题:动态编译基础

          本文链接:https://www.haomeiwen.com/subject/oluuuxtx.html