【发布时间】:2015-10-22 00:48:18
【问题描述】:
假设我有以下课程:
public class SomeClass
{
public int GetValue()
{
return 1;
}
}
检查此方法生成的 IL 代码:
byte[] methodBody = typeof(SomeClass).GetMethod("GetValue").GetMethodBody().GetILAsByteArray();
我们知道methodBody 是:
[0, 23, 10, 43, 0, 6, 42] -- 7 bytes
使用Reflection.Emit 创建我自己的方法:
MethodBuilder methodBuilder = typeBuilder.DefineMethod("GetValue", MethodAttributes.Public, typeof(int), Type.EmptyTypes);
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldc_I4, 1);
il.Emit(OpCodes.Ret);
//....
byte[] dynamicMethodBody = dynamicType.GetMethod("GetValue").GetMethodBody().GetILAsByteArray();
我们知道dynamicMethodBody 是:
[32, 1, 0, 0, 0, 42] -- 6 bytes
为什么两个方法体不同?它们不完全一样吗?
此外,我猜我的dynamicMethodBody 中的前两个字节32 和1 与将常量1 加载到评估堆栈有关,但是为什么这两个字节不存在在methodBody?
【问题讨论】:
标签: c# .net reflection cil reflection.emit