.net 动态方法和函数<;T>;代表

.net 动态方法和函数<;T>;代表,.net,reflection.emit,dynamicmethod,.net,Reflection.emit,Dynamicmethod,我有一个类似这样的类: public class ClassWithFuncConstructor { public ClassWithFuncConstructor(Func<int> func) { } } public void DynamicMethodPrototype() { var instance = new ClassWithFuncConstructor(() => 42); } 如果我们看一下为这个原型编

我有一个类似这样的类:

public class ClassWithFuncConstructor
{
        public ClassWithFuncConstructor(Func<int> func)
    {

    }
}
public void DynamicMethodPrototype()
{   
    var instance = new ClassWithFuncConstructor(() => 42);
}
如果我们看一下为这个原型编译的代码(来自LinqPad),我们可以看到它创建了另一个方法,该方法是函数委托的主体,然后将指向该方法的指针作为构造函数参数传递

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      
DynamicMethodPrototype:
IL_0000:没有
IL_0001:ldsfld UserQuery.CS$9_ucachedanonymousmethoddelegate1
IL_0006:brtrue.s IL_001B
IL_0008:ldnull
IL_0009:ldftn UserQuery.b_0
IL_000F:newobj System.Func..ctor
IL_0014:stsfld UserQuery.CS$9_ucachedanonymousmethoddelegate1
IL_0019:br.s IL_001B
IL_001B:ldsfld UserQuery.CS$9_ucachedanonymousmethoddelegate1
IL_0020:newobj UserQuery+classwithfunconstructor..ctor
IL_0025:stloc.0
IL_0026:ret
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
问题是如何使用
DynamicMethod
类来实现这一点? 我需要创建一个新的匿名方法,也就是
b_u0:
,这样我就可以将对该方法的引用传递给
classwithfunconstructor
类的构造函数


对于
DynamicMethod
类,这可能吗?

您是否尝试过创建另一个
DynamicMethod
并使用第一个方法?您不需要lambda,只需要返回42的函数。