This is another approach to dynamic compilation of objects and their usage via Interfaces.

Introduction

When I read about dynamic compilation in .NET (which is a great feature) for the first time, I soon got stuck with the samples I found. Mostly, they covered the idea of writing small functions dynamically as we can find on various web pages with tutorials. These samples discuss problems like speed of execution or different ways to access the compiled function. But I wanted more. My idea was: I want to compile and use an whole object (or even some more) with members and methods without taking too much care about reflection (yes, some reflection is necessary, I know).

Using the Code

Basically, our best friends here are Microsoft.CSharp and System.CodeDom.Compiler. But to make this simple magic of having an instance of the dynamically compiled object, we also use a simple interface like this:

Hide   Copy Code
using System;
namespace Iface {
public interface ImyInterface
{
string text {get; set;}
int number {get; set;}
int Func (int a, int b);
}
}

To make this interface available to the dynamically compiled code, I put this interface into a calls library, called "Iface.dll".

For the basic program, I add a reference to the Iface.dll and add the namespace together with all others necessary for this example:

Hide   Copy Code
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using Iface;

The code for the dynamically compiled object is as follows:

Hide   Copy Code
const string code=@"
using System;
namespace TestClass
{
public class MyClass : Iface.ImyInterface
{
public int i;
public string text {get; set;}
public int number {get; set;}
public int Func (int a, int b){
i=a+b;
return a+b;
}
}
}
";

As you can see, it's just an implementation of the interface doing nothing special.

For the compilation at runtime, we need a CSharpCodeProvider and CompilerParameters:

Hide   Copy Code
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("Iface.dll");
parameters.GenerateInMemory = true;

Please note: When the program is compiled, a copy of the "Iface.dll" is placed in the same directory as the executable. So, the path for the referenced assembly is limited to "Iface.dll".

Next step: Compilation and some error handling.

Hide   Copy Code
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());
}

And finally we get our object:

Hide   Copy Code
Assembly assembly = results.CompiledAssembly;
Type asmType = assembly.GetType("TestClass.MyClass");
Type[] argTypes=new Type[] { };
ConstructorInfo cInfo=asmType.GetConstructor(argTypes);
ImyInterface myclass=(ImyInterface)cInfo.Invoke(null); int result=myclass.Func(1,2);
Console.WriteLine("and the result is: {0}",result);
Console.ReadKey(true);

Dynamic Compilation and Loading of .NET Objects的更多相关文章

  1. Delphi DLL制作和加载 Static, Dynamic, Delayed 以及 Shared-Memory Manager

    一 Dll的制作一般分为以下几步:1 在一个DLL工程里写一个过程或函数2 写一个Exports关键字,在其下写过程的名称.不用写参数和调用后缀.二 参数传递1 参数类型最好与window C++的参 ...

  2. ora-00600笔记

    一. ORA-600 概述 Errorsof the form ORA-600 are called internal errors. This section clarifies themisund ...

  3. Unity 5 Game Optimization (Chris Dickinson 著)

    1. Detecting Performance Issues 2. Scripting Strategies 3. The Benefits of Batching 4. Kickstart You ...

  4. IronPython Architecture

    [IronPython] IronPython is an implementation of the Python programming language written by the CLR t ...

  5. oracle-Expdp/impdp命令

    建立逻辑路径 create or replace directory dumpdir as 'c:\'; grant read,write on directory dumpdir to scott; ...

  6. Orchard源码分析(5.1):Host初始化(DefaultOrchardHost.Initialize方法)

    概述 Orchard作为一个可扩展的CMS系统,是由一系列的模块(Modules)或主题(Themes)组成,这些模块或主题统称为扩展(Extensions).在初始化或运行时需要对扩展进行安装:De ...

  7. [你必须知道的.NET]第三十一回,深入.NET 4.0之,从“新”展望

    发布日期:2009.05.22 作者:Anytao © 2009 Anytao.com ,Anytao原创作品,转贴请注明作者和出处. /// <summary> /// 本文开始,将以& ...

  8. SCI&EI 英文PAPER投稿经验【转】

    英文投稿的一点经验[转载] From: http://chl033.woku.com/article/2893317.html 1. 首先一定要注意杂志的发表范围, 超出范围的千万别投,要不就是浪费时 ...

  9. 【转载】Android Studio 设置内存大小及原理

    http://www.cnblogs.com/justinzhang/p/4274985.html http://tsroad.lofter.com/post/376316_69363ae Andro ...

随机推荐

  1. echarts 有关饼形图和map的使用技巧1(饼图)

    http://blog.csdn.net/yhn1121/article/details/52041742 先上个链接,百度无意间搜到的,写得比我全面,可以直接飞去看它: 之前写网页用过echarts ...

  2. Xcode 4.1实用小工具:模拟网络连接和带宽

    暂无评论 适用于Mac OS X Lion的开发套件Xcode 4.1中,有个新鲜的小工具叫做Network Link Conditioner(网络连接调节器),是一款具有高度可定制性的辅助工具,让用 ...

  3. Linux系统下MySql表名大小写敏感问题

    mysql是通过lower_case_table_names变量来处理大小写问题的. 首先查询该变量 mysql在Linux下数据库名.表名.列名.表别名大小写规则如下: 1.数据库名与表名严格区分大 ...

  4. idea 下运行安卓项目

    修改 gralde 路径修改安卓sdk路径进入project structure 设置 Project settings / Project /project SDK 选择 Android API 2 ...

  5. C++入门经典-例2.4-使用scanf格式输入函数得到用户输入的数据

    1:puts函数可以输出提示信息的字符串. 2:代码如下: // 2.4.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" int main( ...

  6. DH加密算法

    http://blog.csdn.net/zbw18297786698/article/details/53609794

  7. 套接字之 getsockname && getpeername

    getsockname-获取本地地址:比如,在绑定的时候设置端口号为0由系统自动选择端口绑定,或者使用了INADDR_ANY通配所有地址的情况下,后面需要用到具体的地址和端口,就可以用getsockn ...

  8. 套接字之recv系统调用

    recv系统调用对sys_recvfrom进行了简单的封装,只是其中不包含地址信息,其只需要从建立连接的另一端接收信息: /* * Receive a datagram from a socket. ...

  9. 第七周课程总结 & 实验报告(五)

    第七周课程总结 一.抽象类与接口的应用 1.实例化 2.实际应用 ---模板设计(抽象类) ---制定标准(接口) 3.设计模式 ---工厂设计 ---代理设计 ---适配器设计 二.抽象类与接口之间 ...

  10. 浅谈Manacher算法

    Manacher manacher是一种\(O(n)\)求最长回文子串的算法,俗称马拉车(滑稽) 直接步入正题 首先可以知道的是:每一个回文串都有自己的对称中心,相应的也有自己的最大延伸长度(可以称之 ...