为匿名方法生成IL

Upu*_*ara 5 .net clr il

我想为多线程应用程序生成IL.作为第一步,我编写了一个简单的应用程序并进行了检查,使用ILSpy生成了IL.

public class ThreadTesting
{
    public static void Main()
    {
        Thread thread = new Thread(() => Print("Hello from t!"));
        thread.Start();
    }

    public static void Print(string message)
    {
        Console.WriteLine(message);
    }
}
Run Code Online (Sandbox Code Playgroud)
.method public hidebysig static 
    void Main () cil managed 
{
    // Method begins at RVA 0x2060
    // Code size 46 (0x2e)
    .maxstack 3
    .entrypoint
    .locals init (
        [0] class [mscorlib]System.Threading.Thread
    )

    IL_0000: nop
    IL_0001: ldsfld class [mscorlib]System.Threading.ThreadStart ThreadTesting::'CS$<>9__CachedAnonymousMethodDelegate1'
    IL_0006: brtrue.s IL_001b

    IL_0008: ldnull
    IL_0009: ldftn void ThreadTesting::'<Main>b__0'()
    IL_000f: newobj instance void [mscorlib]System.Threading.ThreadStart::.ctor(object, native int)
    IL_0014: stsfld class [mscorlib]System.Threading.ThreadStart ThreadTesting::'CS$<>9__CachedAnonymousMethodDelegate1'
    IL_0019: br.s IL_001b

    IL_001b: ldsfld class [mscorlib]System.Threading.ThreadStart ThreadTesting::'CS$<>9__CachedAnonymousMethodDelegate1'
    IL_0020: newobj instance void [mscorlib]System.Threading.Thread::.ctor(class [mscorlib]System.Threading.ThreadStart)
    IL_0025: stloc.0
    IL_0026: ldloc.0
    IL_0027: callvirt instance void [mscorlib]System.Threading.Thread::Start()
    IL_002c: nop
    IL_002d: ret
} // end of method ThreadTesting::Main
Run Code Online (Sandbox Code Playgroud)

我能够使用System.Reflection.Emit命名空间生成大多数上述IL代码.

不幸的是我无法弄清楚如何使用System.Reflection.Emit生成以下IL代码.

IL_0001: ldsfld class [mscorlib]System.Threading.ThreadStart ThreadTesting::'CS$<>9__CachedAnonymousMethodDelegate1'
Run Code Online (Sandbox Code Playgroud)

那么有人可以帮我弄清楚如何为匿名方法生成IL吗?

Mar*_*ell 6

IL只是编译器缓存委托实例的方式 - 它不是方法本身的一部分.如果您正在使用DynamicMethod(您可能应该这样做),那么只需调用CreateDelegate({您的委托类型}),将其转换为您想要的委托类型(可能是ThreadStart),并将(类型的)委托实例存储在任何位置.