using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text; namespace System
{
public static class CompileCSCAtRuntime
{
public static void HelloWorld()
{
string code = @"
using System; namespace First
{
public class Program
{
public static void Main()
{
" +
"Console.WriteLine(\"Hello, world!\");"
+ @"
}
}
}
"; CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters(); // Reference to System.Drawing library
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
// True - memory generation, false - external file generation
parameters.GenerateInMemory = true;
// True - exe file generation, false - dll file generation
parameters.GenerateExecutable = true; CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.HasErrors)
{
StringBuilder sb = new StringBuilder(); foreach (CompilerError error in results.Errors)
{
sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
} throw new InvalidOperationException(sb.ToString());
} Assembly assembly = results.CompiledAssembly;
Type program = assembly.GetType("First.Program");
MethodInfo main = program.GetMethod("Main"); main.Invoke(null, null);
} public static void TestMeothds()
{
MethodInfo function = CreateFunction("x + 2 * y");
var betterFunction = (Func<double, double, double>)Delegate.CreateDelegate(typeof(Func<double, double, double>), function);
Func<double, double, double> lambda = (x, y) => x + 2 * y; DateTime start;
DateTime stop;
double result;
int repetitions = 5000000; start = DateTime.Now;
for (int i = 0; i < repetitions; i++)
{
result = OriginalFunction(2, 3);
}
stop = DateTime.Now;
Console.WriteLine("Original - time: {0} ms", (stop - start).TotalMilliseconds); start = DateTime.Now;
for (int i = 0; i < repetitions; i++)
{
result = (double)function.Invoke(null, new object[] { 2, 3 });
}
stop = DateTime.Now;
Console.WriteLine("Reflection - time: {0} ms", (stop - start).TotalMilliseconds); start = DateTime.Now;
for (int i = 0; i < repetitions; i++)
{
result = betterFunction(2, 3);
}
stop = DateTime.Now;
Console.WriteLine("Delegate - time: {0} ms", (stop - start).TotalMilliseconds); start = DateTime.Now;
for (int i = 0; i < repetitions; i++)
{
result = lambda(2, 3);
}
stop = DateTime.Now;
Console.WriteLine("Lambda - time: {0} ms", (stop - start).TotalMilliseconds);
} public static double OriginalFunction(double x, double y)
{
return x + 2 * y;
} public static MethodInfo CreateFunction(string function)
{
string code = @"
using System; namespace UserFunctions
{
public class BinaryFunction
{
public static double Function(double x, double y)
{
return func_xy;
}
}
}
"; string finalCode = code.Replace("func_xy", function); CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(), finalCode); Type binaryFunction = results.CompiledAssembly.GetType("UserFunctions.BinaryFunction");
return binaryFunction.GetMethod("Function");
}
}
}

  

编译C#代码的更多相关文章

  1. (转载)JAVA动态编译--字节代码的操纵

    在一般的Java应用开发过程中,开发人员使用Java的方式比较简单.打开惯用的IDE,编写Java源代码,再利用IDE提供的功能直接运行Java 程序就可以了.这种开发模式背后的过程是:开发人员编写的 ...

  2. 几款比较好用的C语言的集成开发环境及在windows下用命令行编译C代码

    最近要用到C,所以尝试了这几款windows平台下比较好的IDE. VS2015:比较复杂和庞大,据说从2013版本开始支持C99标准. C-free:轻巧,但是不支持C99. vc++6.0:很多学 ...

  3. GCC编译C代码

    C程序的编译过程       常用文件的后缀名: gcc编译c代码 1.gcc 常用编译选项: 2.gcc编译方法 testc.c: #include <stdio.h> int main ...

  4. JD-GUI反编译后代码逻辑分析

    一,用jd-gui.exe等工具查看源代码.如何你不会,可以参看此文章: http://blog.csdn.net/hp_2008/article/details/8207879 可以到以下连接下载可 ...

  5. 理解Babel是如何编译JS代码的及理解抽象语法树(AST)

    Babel是如何编译JS代码的及理解抽象语法树(AST) 1. Babel的作用是?   很多浏览器目前还不支持ES6的代码,但是我们可以通过Babel将ES6的代码转译成ES5代码,让所有的浏览器都 ...

  6. 使用gulp和bable实现实时编译ES6代码

    这篇文章最初发表在我自己折腾的博客站点上:使用gulp和bable实现实时编译ES6代码,该博客用了一位前辈开源的源码,基于thinkjs和vuejs开发,欢迎大家来逛逛. 问题描述> 项目开发 ...

  7. [UE4]使用UnrealVS扩展快速编译C++代码

    一.如果UE4 编辑器已经打开,则VS中的重新生成项目将不能使用,一定要关了UE4 编辑器才可以.一般不是有VS自身的编译UE4的C++代码 二.epic提供了UnrealVS扩展,可以快速编译C++ ...

  8. AndroidStudio用Cmake方式编译NDK代码(cmake配置.a库)

    1.cmake是什么? CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程).他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C+ ...

  9. Android Apk的反编译与代码混淆

    一.反编译 1.获取工具: 既然是反编译,肯定要用到一些相关的工具,工具可以到这里下载,里面包含三个文件夹,用于反编译,查看反编译之后的代码: 其实这两工具都是google官方出的,也可在google ...

  10. 缓冲区溢出实战教程系列(二):dev c++编译汇编代码

    小伙伴们对我上一篇文章的反应完全出乎了我的意料,感谢大家对我的支持和认可.接下来我会精心的把这一系列课程设计好,尽量详细的展示给大家.上篇文章我列举了一个缓冲区溢出的小例子,并提到了dev c++.o ...

随机推荐

  1. SQL Server的小数数值类型(float 和 decimal)用法

    在SQL Server中,小数数值实际上只有两种数据类型:float 和 decimal.double precision 整体是数据类型,等价于 float(53),real等价于float(24) ...

  2. How to load a local .CSS file & JavaScript resources using iPhone UIWebView Class

    This post will cover the basic setup and creation of an application with web content for iPhone that ...

  3. ASP.NET MVC 4.0中选择Windows 验证默认出错拒绝访问的原因和解决方案

    在VS 2012或者2013 中,根据模板创建一个ASP.NET MVC 4.0的应用程序,选择下面的模板 然后选择Intranet Application 不对源代码做任何修改,直接按下F5调试,会 ...

  4. bootstrap插件思路整理

    知识有时也需温故知新嘛,本次做一次bs插件梳理. $.support.transition 通过判断自定义元素是否支持WebkitTransition.MozTransition.OTransitio ...

  5. PetaPoco 访问SQL SERVER 存储过程

    博客园有篇文章<小巧方便的ORM类库——PetaPoco>  介绍了PetaPoco调用存储过程: //调用存储过程 db.Execute("exec procSomeHandl ...

  6. Elasticsearch——分词器对String的作用

    更多内容参考:Elasticsearch学习总结 关于String类型--分词与不分词 在Elasticsearch中String是最基本的数据类型,如果不是数字或者标准格式的日期等这种很明显的类型, ...

  7. linux service命令解析

      我们平时都会用service xxx start来启动某个进程,那么它背后究竟执行了什么? 其实service的绝对路径为/sbin/service ,打开这个文件cat /sbin/servic ...

  8. SQL Server获取下一个编码字符实现继续重构与增强

        我在SQL Server获取下一个编码字符实现的博文中,虽然实现了这个问题,但是感觉维护起来比较麻烦,例如如果调整编码字符串的固定长度,就需要变更三个函数,这样的为何成本确实比较大.面向对象编 ...

  9. SQL 聚合函数

    SQL聚合函数 MAX---最大值 MIN--最小值 AVG--平均值 SUM--求和 COUNT--记录的条数 EXample: --从MyStudent表中查询最大年龄,最小年龄,平均年龄,年龄的 ...

  10. IOS ID生成器

    // // IdGenerator.m // Copyright (c) 2014年 青岛拓宇网络科技有限公司. All rights reserved. // #import "IdGen ...