为什么一个打字机会吐出两个.ctor方法?

时间:2008-11-02 09:09:55

标签: c# .net vb.net

我有一个类型构建器,它生成两个相同的.ctor,一个没有方法体,另一个有所有init代码。

我从另一个类型和属性定义一个字段来访问该类型,因此需要在.ctor中初始化它

我应该从哪里开始寻找

代码如下

Public Sub ctor(ByVal type As TypeBuilder, ByVal FieldRefs As Dictionary(Of Type, FieldBuilder))
    ' Method attributes
    Dim methodAttributes As System.Reflection.MethodAttributes = MethodAttributes.[Public]

    Dim method As MethodBuilder = type.DefineMethod(".ctor", methodAttributes)
    ' Preparing Reflection instances

    Dim ctor1 As ConstructorInfo = GetType(Object).GetConstructor(BindingFlags.Instance Or BindingFlags.[Public] Or BindingFlags.NonPublic, Nothing, Nothing, Nothing)

    ' Setting return type
    method.SetReturnType(GetType(Void))
    ' Adding parameters
    Dim gen As ILGenerator = method.GetILGenerator()
    ' Writing body
    gen.Emit(OpCodes.Ldarg_0)
    gen.Emit(OpCodes.[Call], ctor1)

    'new up fields
    For Each item In FieldRefs
        AddCtor(type, gen, item.Value, item.Key)
    Next

    gen.Emit(OpCodes.Ret)

    ' finished
End Sub


Private Sub AddCtor(ByVal type As TypeBuilder, ByVal gen As ILGenerator, ByVal FieldBuilderRef As FieldBuilder, ByVal TypeToReference As Type)
    Dim TypeCtor = TypeToReference.GetConstructor(BindingFlags.Instance Or BindingFlags.[Public] Or BindingFlags.NonPublic, Nothing, New Type() {}, Nothing)
    gen.Emit(OpCodes.Ldarg_0)
    gen.Emit(OpCodes.Newobj, TypeCtor)
    gen.Emit(OpCodes.Stfld, FieldBuilderRef)
End Sub

代码接收类型字典,字段构建器在ctor中发出。新建早期在typebuilder主程序中构建的字段

1 个答案:

答案 0 :(得分:1)

你确定一个不是.cctor吗?但是你负责在TypeBuilder中创建所有构造函数;除了DefineDefaultConstructor()之外,你有没有打电话给DefineConstructor()?这将创建一个空的默认构造函数...所以如果你不想要一个构造函数,不要调用它。