开发者论坛

 找回密码
 注册 (请使用非IE浏览器)
查看: 4648|回复: 3

[教程] C#动态编译代码到内存,并调用执行。

[复制链接]

0

精华

5097

贡献

5311

赞扬

管理员

帖子
1154
软币
21035
在线时间
4325 小时
注册时间
2013-6-7

黄马甲

发表于 2014-8-17 22:27:51 | 显示全部楼层 |阅读模式

[C#] 纯文本查看 复制代码
using System;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
public static void compiler()
        {
            string codeString = @"
            public class CompilerTest 
            {
                public static string GetTestString()
                {
                    string MyStr = ""This is a Dynamic Compiler Demo!"";
                    return MyStr;
                }
            }";
            CompilerParameters compilerParams = new CompilerParameters()
            {
                //编译器选项设置
                CompilerOptions = "/target:library /optimize",
                //编译时在内存输出
                GenerateInMemory = true,
                //生成调试信息
                IncludeDebugInformation = false
            };
            //添加相关的引用
            compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");
            //ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
            CSharpCodeProvider compiler = new CSharpCodeProvider(
                new System.Collections.Generic.Dictionary<string, string>() { { "CompilerVersion", "v4.0" } }
            ); 
            //编译
            CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, codeString);
            //创建程序集
            Assembly asm = results.CompiledAssembly;

            //获取编译后的类型
            object objMyTestClass = asm.CreateInstance("CompilerTest");
            Type MyTestClassType = objMyTestClass.GetType();
            //输出结果
            Console.WriteLine(MyTestClassType.GetMethod("GetTestString").Invoke(objMyTestClass, null));
            Console.ReadLine();
        }



回复

使用道具 举报

0

精华

0

贡献

24

赞扬

帖子
7
软币
147
在线时间
3 小时
注册时间
2014-9-23
发表于 2015-5-13 09:05:19 | 显示全部楼层
这个吊,支持!
回复

使用道具 举报

0

精华

0

贡献

0

赞扬

帖子
24
软币
214
在线时间
17 小时
注册时间
2015-6-16
发表于 2015-6-21 16:13:20 | 显示全部楼层
真牛比,太吊了,支持
回复

使用道具 举报

Archiver|手机版|小黑屋|开发者网 ( 苏ICP备08004430号-2 )
版权所有:南京韵文教育信息咨询有限公司

GMT+8, 2024-5-3 20:24

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表