问题
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 nop
s 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