I have a class that looks like this:
public class ClassWithFuncConstructor
{
public ClassWithFuncConstructor(Func<int> func)
{
}
}
Now I want to use the DynamicMethod
class to emit the code needed to create an instance of the ClassWithFuncConstructor
class like this:
public void DynamicMethodPrototype()
{
var instance = new ClassWithFuncConstructor(() => 42);
}
If we take a look at the code compiled for this prototype (from LinqPad), we can see that it creates another method that is the body of the function delegate and then passes a pointer to that method as the constructor parameter.
DynamicMethodPrototype:
IL_0000: nop
IL_0001: ldsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0006: brtrue.s IL_001B
IL_0008: ldnull
IL_0009: ldftn UserQuery.<DynamicMethodPrototype>b__0
IL_000F: newobj System.Func<System.Int32>..ctor
IL_0014: stsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0019: br.s IL_001B
IL_001B: ldsfld UserQuery.CS$<>9__CachedAnonymousMethodDelegate1
IL_0020: newobj UserQuery+ClassWithFuncConstructor..ctor
IL_0025: stloc.0
IL_0026: ret
<DynamicMethodPrototype>b__0:
IL_0000: ldc.i4.s 2A
IL_0002: stloc.0
IL_0003: br.s IL_0005
IL_0005: ldloc.0
IL_0006: ret
The question is how could this be done the use of the DynamicMethod
class?
I need to sort of create a new anonymous method aka the <DynamicMethodPrototype>b__0:
so that I can pass a reference to that method to the constructor of the ClassWithFuncConstructor
class.
Is this even possible to do with the DynamicMethod
class?