System.Reflection.Emit的一个很重要的发现.

在同一个ModuleBuilder里, DefineType并且CreateType之后, 是可以继续DefineType的..
这样可以防止编译多次代码导致的AssemblyBuilder过多的问题. 现在只需要1个AssemblyBuilder就够了.
这个发现对于WEB框架非常有意义. 因为WEB框架包含大量的脚本文件. 有了这个特征, 脚本文件可以很放心地分开来编译了
 
 
   
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;


static public class EmitTest
{
static public void Go()
{
AssemblyBuilder asm
= AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName( " EmitTest " ), AssemblyBuilderAccess.Run);
ModuleBuilder mdl
= asm.DefineDynamicModule( " EmitTestModule " );

RunType(mdl,
" Type1 " , " Method1 " , " Hello " );
RunType(mdl,
" Type2 " , " Method2 " , " World " );
}

private static void RunType(ModuleBuilder mdl, string typename
,
string methodname, string writestring)
{
TypeBuilder t1
= mdl.DefineType(typename);
MethodBuilder mb1
= t1.DefineMethod(methodname
, MethodAttributes.Static
| MethodAttributes.Public, typeof ( void ), new Type[] { });
ILGenerator g1
= mb1.GetILGenerator();
g1.Emit(OpCodes.Ldstr, writestring);
g1.Emit(OpCodes.Call,
typeof (EmitTest).GetMethod( " WriteLine " ));
MethodInfo mi1
= t1.CreateType().GetMethod(methodname);
mi1.Invoke(
null , null );
}

[System.Runtime.CompilerServices.MethodImpl(
System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static public void WriteLine( string str)
{
MethodBase caller
= new System.Diagnostics.StackFrame( 1 ).GetMethod();
Console.WriteLine(caller.DeclaringType.Assembly.FullName);
Console.WriteLine(str);
}
}
 
 

转载于:https://www.cnblogs.com/parallet/archive/2011/06/22/2086798.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值