Inline MSIL/CIL

二次信任 提交于 2019-12-22 08:55:07

问题


I created following simple method:

public static void Main () {
    Console.WriteLine("Hello world!");
    Console.ReadKey(true);
}

Then I used ILSpy to get the MSIL code:

.method public hidebysig static void Main() cil managed {
    .entrypoint
    .maxstack  8
    nop
    ldstr "Hello world!"
    call void [mscorlib]System.Console::WriteLine(string)
    nop
    ldc.i4.1
    call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey(bool)
    pop
    ret
}

Finally I tried to write the MSIL code into my C# code using the #if IL trick that I've found here.

public static void Main () {
    #if IL
        nop
        ldstr "Hello world!"
        call void [mscorlib]System.Console::WriteLine(string)
        nop
        ldc.i4.1
        call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey(bool)
        pop
        ret
    #else
        Console.WriteLine("Hello world!");
        Console.ReadKey(true);
    #endif
}

I tried this trick with and without the nops and with and without the #else, but Visual Studio never compiled the MSIL code. Where is my mistake or is there another way (if there is a way) to write MSIL code into C# code?

来源:https://stackoverflow.com/questions/20955717/inline-msil-cil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!