2011-06-07 92 views
4

我想使用System.Reflection.Emit命名空间为2D阵列构造生成IL。为2D阵列生成IL

我的C#代码是

Array 2dArr = Array.CreateInstance(typeof(int),100,100); 

使用ildasm,我意识到,以下IL代码是上述 C#代码生成的。

IL_0006: call  class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) 
IL_000b: ldc.i4.s 100 
IL_000d: ldc.i4.s 100 
IL_000f: call  class [mscorlib]System.Array [mscorlib]System.Array::CreateInstance(class [mscorlib]System.Type, 
                          int32, 
                          int32) 

我能够生成最后三条IL语句,如下所示。

MethodInfo createArray = typeof(Array).GetMethod("CreateInstance", 
       new Type[] { typeof(Type),typeof(int),typeof(int) }); 
gen.Emit(OpCodes.Ldc_I4_1); 
      gen.Emit(OpCodes.Ldc_I4_1); 
      gen.Emit(OpCodes.Call, createArray); 

但我没有关于如何生成拳头IL语句清晰的概念(即IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) )

你有什么想法?

此外,有人可以指出一些关于如何使用System.Reflection.Emit命名空间以生成IL代码的好教程/文档?

回答

8

啊,好ol'typeof;是的,那就是:

il.Emit(OpCodes.Ldtoken, typeof(int)); 
il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null); 

重新引导......我的绝招,如果我遇到问题总是“编译类似的东西,看看它在反射器”。

如果你想要一些例子dapper-dot-netprotobuf-net都做IL,像样的数目 - 第一个是多个内含,有限的和可以理解的;第二个是全力以赴的,没有任何禁止的疯狂的IL。

的提示IL:

  • 在屏幕
  • 用树枝等的短期形式的右手边的每一步跟踪意见堆,但只有当你知道你使用它们有一个非常本地的分支
  • 为自己写一些实用方法,即使对于加载一个整数这样的简单事情来说(这实际上相当复杂,因为有12种不同的加载int-32的方式,取决于值)
+0

非常感谢,这真的帮助我 – 2011-06-07 18:12:05