.NET 动态生成方法

using System;
using System.Reflection;
using System.Reflection.Emit;

class Demo
{
    static void Main()
    {
        DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(void), Type.EmptyTypes, typeof(Demo), false);
        DynamicILInfo il = dm.GetDynamicILInfo();

        SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();
        il.SetLocalSignature(sigHelper.GetSignature());

        byte[] code = { 0x00, 0x72, 0x01, 0x00, 0x00, 0x70, 0x28, 0x04, 0x00, 0x00, 0x0a, 0x00, 0x2a };
        int token0 = il.GetTokenFor("Hello world");
        int token1 = il.GetTokenFor(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }).MethodHandle);
        PutInteger4(token0, 0x0002, code);
        PutInteger4(token1, 0x0007, code);
        il.SetCode(code, 8);

        dm.Invoke(null, null);
       Console.Read();
    }

    static void PutInteger4(int value, int startPos, byte[] array)
    {
        array[startPos++] = (byte)value;
        array[startPos++] = (byte)(value >> 8);
        array[startPos++] = (byte)(value >> 16);
        array[startPos++] = (byte)(value >> 24);
    }
}
.method public hidebysig static void HelloWorld() cil managed
// SIG: 00 00 01
{
  // Method begins at RVA 0x2050
  // Code size 13 (0xd)
  .maxstack 8
  IL_0000: /* 00 |             */ nop
  IL_0001: /* 72 | (70)000001 */ ldstr "Hello world"
  IL_0006: /* 28 | (0A)000004 */ call void [mscorlib]System.Console::WriteLine(string)
  IL_000b: /* 00 |             */ nop
  IL_000c: /* 2A |             */ ret
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值