惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
Intezer
The Register - Security
The Register - Security
博客园 - 三生石上(FineUI控件)
博客园_首页
量子位
Hugging Face - Blog
Hugging Face - Blog
Engineering at Meta
Engineering at Meta
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
GbyAI
GbyAI
D
Docker
M
MIT News - Artificial intelligence
Jina AI
Jina AI
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
有赞技术团队
有赞技术团队
IT之家
IT之家
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
Cyberwarzone
Cyberwarzone
Recorded Future
Recorded Future
H
Help Net Security
L
LINUX DO - 热门话题
罗磊的独立博客
Google DeepMind News
Google DeepMind News
NISL@THU
NISL@THU
SecWiki News
SecWiki News
T
Threat Research - Cisco Blogs
T
Threatpost
Cloudbric
Cloudbric
G
GRAHAM CLULEY
S
Security @ Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
P
Proofpoint News Feed
V2EX - 技术
V2EX - 技术
L
LangChain Blog
The Cloudflare Blog
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
B
Blog
T
The Blog of Author Tim Ferriss

博客园 - Danny Chen

python asyncio 获取协程返回值和使用callback c#等待所有子线程执行完毕方法 Python virtualenv 查看当前正在运行的python进程 Mac 删除/卸载 自己安装的python python读取txt文件最后一行(文件大+文件小) pycharm 注册码/License server 2017年最新 Linux cat命令详解 在Mac平台上安装配置ELK时的一些总结 Mac上搭建ELK C#中用schema验证xml的合法性 C#中XML与对象之间的序列化、反序列化 C#位运算 SQL Server 权限管理 [C#]手把手教你打造Socket的TCP通讯连接(一) C#动态调用WCF接口,两种方式任你选。 动态调用WCF服务 矩阵的坐标变换(转) 【.NET线程--进阶(一)】--线程方法详解
如何用C#动态编译、执行代码
Danny Chen · 2017-06-16 · via 博客园 - Danny Chen

在开始之前,先熟悉几个类及部分属性、方法:CSharpCodeProviderICodeCompilerCompilerParametersCompilerResultsAssembly

  一、CSharpCodeProvider
    提供对C#代码生成器和代码编译器的实例的访问。如果要动态生成VB代码,可以使用VBCodeProvider

    CreateCompiler():获取编译器的实例。

  二、ICodeCompiler
    定义用于调用源代码编译的接口或使用指定编译器的CodeDOM树。每种编译方法都接受指示编译器的CompilerParameters对象,并返回指示编译结果的CompilerResults对象。

    CompilerAssemblyFromSource(CompilerParameters option, string source):使用指定的编译器,从包含源代码的字符串设置编译程序集。

  三、CompilerParameters
    表示用于调用编译器的参数。

    ReferencedAssemblies:获取当前项目所引用的程序集。Add方法为程序集添加引用。
    GenerateExecutable:获取或设置一个值,该值指示是否生成可执行文件。若此属性为false,则生成DLL,默认是false。
    GenerateInMemory:获取或设置一个值,该值指示是否在内存中生成输出。

  四、CompilerResults
    表示从编译器返回的编译结果。

    CompiledAssembly:获取或设置以编译的程序集,Assembly类型。

  五、Assembly
    就是程序集了(不知道如何描述了)。

  大致了解了以上知识之后,就可以使用C#动态的编译并执行代码了,一下是一段示例程序:

using System; 
using System.Reflection; 
using System.Globalization; 
using Microsoft.CSharp;
using System.CodeDom; 
using System.CodeDom.Compiler;
using System.Text; 

namespace ConsoleApplication1 
{
    public class Program
    {
        static void Main(string[] args)
        {
            // 1.CSharpCodePrivoder
            CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();

            // 2.ICodeComplier
            ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();

            // 3.CompilerParameters
            CompilerParameters objCompilerParameters = new CompilerParameters();
            objCompilerParameters.ReferencedAssemblies.Add("System.dll");
            objCompilerParameters.GenerateExecutable = false;
            objCompilerParameters.GenerateInMemory = true;

            // 4.CompilerResults
            CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode());

            if (cr.Errors.HasErrors)
            {
                Console.WriteLine("编译错误:");
                foreach (CompilerError err in cr.Errors)
                {
                    Console.WriteLine(err.ErrorText);
                }
            }
            else
            {
                // 通过反射,调用HelloWorld的实例
                Assembly objAssembly = cr.CompiledAssembly;
                object objHelloWorld = objAssembly.CreateInstance("DynamicCodeGenerate.HelloWorld");
                MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut");

                Console.WriteLine(objMI.Invoke(objHelloWorld, null));
            }

            Console.ReadLine();
        }

        static string GenerateCode()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("using System;");
            sb.Append(Environment.NewLine);
            sb.Append("namespace DynamicCodeGenerate");
            sb.Append(Environment.NewLine);
            sb.Append("{");
            sb.Append(Environment.NewLine);
            sb.Append("    public class HelloWorld");
            sb.Append(Environment.NewLine);
            sb.Append("    {");
            sb.Append(Environment.NewLine);
            sb.Append("        public string OutPut()");
            sb.Append(Environment.NewLine);
            sb.Append("        {");
            sb.Append(Environment.NewLine);
            sb.Append("             return \"Hello world!\";");
            sb.Append(Environment.NewLine);
            sb.Append("        }");
            sb.Append(Environment.NewLine);
            sb.Append("    }");
            sb.Append(Environment.NewLine);
            sb.Append("}");

            string code = sb.ToString();
            Console.WriteLine(code);
            Console.WriteLine();

            return code;
        }
    }
}