开发者

IL, emit default constructor call

开发者 https://www.devze.com 2023-03-23 01:03 出处:网络
I\'m generating new type at runtime, After I\'ve generated default constructor I want to generate another one, with parameters.I\'m doing it this way :

I'm generating new type at runtime, After I've generated default constructor I want to generate another one, with parameters.I'm doing it this way :

cb = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
                    CallingConventions.Standard, ne开发者_JAVA百科w Type[] { typeof(bool) });
GenConstructorWithParameters(cb, fields, genFields);

The problem is, that I am unable to call default constructor from method GenConstructorWithParameters, because CLR does not allow me to write something like this :

gen.Emit(OpCodes.Ldarg_0);        
gen.Emit(OpCodes.Call, cb.DeclaringType.GetConstructor(Type.EmptyTypes));//Not allowed to call .GetConstructor() on not created type!

How do I emit call to default constructor? Is it possible at all?

tb - instance of TypeBuilder, cb - ConstructorBuilder


Rather than using DeclaringType.GetConstructor, you should pass your current ConstructorBuilder for the default constructor.

Basically, whilst building up a type, in places where you might use reflection based methods on existing types, you should instead pass in the builders that you're already working with.


So it would be:

gen.Emit(OpCodes.Call, defaultCB);

where defaultCB was the ConstructorBuilder you declared when defining the default constructor.


You want newobj:

gen.Emit(OpCodes.Newobj, cb.DeclaringType.GetConstructor(Type.EmptyTypes));


Dim objCtor As ConstructorInfo = objType.GetConstructor(New Type() {})

      Dim pointCtor As ConstructorBuilder = pointTypeBld.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctorParams)
      Dim ctorIL As ILGenerator = pointCtor.GetILGenerator()

      ctorIL.Emit(OpCodes.Ldarg_0)
      ctorIL.Emit(OpCodes.Call, objCtor)

      ctorIL.Emit(OpCodes.Ldarg_0)
      ctorIL.Emit(OpCodes.Ldarg_1)
      ctorIL.Emit(OpCodes.Stfld, xField)

      ctorIL.Emit(OpCodes.Ldarg_0)
      ctorIL.Emit(OpCodes.Ldarg_2)
      ctorIL.Emit(OpCodes.Stfld, yField)

      ctorIL.Emit(OpCodes.Ldarg_0)
      ctorIL.Emit(OpCodes.Ldarg_3)
      ctorIL.Emit(OpCodes.Stfld, zField)

      ctorIL.Emit(OpCodes.Ret)

Dim myDynamicType As Type = Nothing
Dim myDTctor As ConstructorInfo = myDynamicType.GetConstructor(aPtypes)
      Console.WriteLine("Constructor: {0};", myDTctor.ToString())
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号