dot net IL 使用笔记
MethodBuilder mb1 = tb.DefineMethod( "CallA",
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
null,
null );
ILGenerator MethodILObj = mb1.GetILGenerator();
//新建一个局部变量,数据类型是A
LocalBuilder loc = MethodILObj.DeclareLocal( typeof( A ) );
//调用A的无参数构造函数来新建一个A类的对象
MethodILObj.Emit( OpCodes.Newobj, typeof( A ).GetConstructor( new Type[ 0 ] ) );
//把A刚新建的对象,赋值给局部变量,他的索引是0
MethodILObj.Emit( OpCodes.Stloc_0 );
//读取索引为0的局部变量到内存流
MethodILObj.Emit( OpCodes.Ldloc_0 );
//加载字符串到内存流
MethodILObj.Emit( OpCodes.Ldstr, "Set MM Property OK." );
//把刚刚加载的字符串赋值给叫作Mm的属性,对象就是刚刚加载的索引为0的局部变量
MethodILObj.Emit( OpCodes.Call, typeof( A ).GetProperty( "Mm" ).GetSetMethod() );
//读取索引为0的局部变量到内存流
MethodILObj.Emit( OpCodes.Ldloc_0 );
//调用内存流对象的HelloWorld方法
MethodILObj.Emit( OpCodes.Call, typeof( A ).GetMethod( "HelloWorld" ) );
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
null,
null );
ILGenerator MethodILObj = mb1.GetILGenerator();
//新建一个局部变量,数据类型是A
LocalBuilder loc = MethodILObj.DeclareLocal( typeof( A ) );
//调用A的无参数构造函数来新建一个A类的对象
MethodILObj.Emit( OpCodes.Newobj, typeof( A ).GetConstructor( new Type[ 0 ] ) );
//把A刚新建的对象,赋值给局部变量,他的索引是0
MethodILObj.Emit( OpCodes.Stloc_0 );
//读取索引为0的局部变量到内存流
MethodILObj.Emit( OpCodes.Ldloc_0 );
//加载字符串到内存流
MethodILObj.Emit( OpCodes.Ldstr, "Set MM Property OK." );
//把刚刚加载的字符串赋值给叫作Mm的属性,对象就是刚刚加载的索引为0的局部变量
MethodILObj.Emit( OpCodes.Call, typeof( A ).GetProperty( "Mm" ).GetSetMethod() );
//读取索引为0的局部变量到内存流
MethodILObj.Emit( OpCodes.Ldloc_0 );
//调用内存流对象的HelloWorld方法
MethodILObj.Emit( OpCodes.Call, typeof( A ).GetMethod( "HelloWorld" ) );

浙公网安备 33010602011771号