动态编译基础

一. 将函数或方法放在文本文件或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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,002评论 25 709
  • 在此特此声明:一下所有链接均来自互联网,在此记录下我的查阅学习历程,感谢各位原创作者的无私奉献 ! 技术一点一点积...
    远航的移动开发历程阅读 11,333评论 12 197
  • 一、温故而知新 1. 内存不够怎么办 内存简单分配策略的问题地址空间不隔离内存使用效率低程序运行的地址不确定 关于...
    SeanCST阅读 7,900评论 0 27
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,107评论 19 139
  • 前几天,正当我在群聊里习惯性的以老大的姿态教育老二和老三时,老弟突然说“姐,你开个个人公众号吧”,可能他觉得...
    大芳姐阅读 291评论 0 0