Vra

I am trying to programmatically define a class with a base class, and a constructor which calls the base constructor. Part of the subclass constructor's job is to initialize a string called name with a value. But no matter what I try name remains null. The base constructor works fine because some arraylists are initialized etc. Typesignature is a string. The field name already exists in the base class.

FieldBuilder fbname = tb.DefineField("name", typeof(string), FieldAttributes.Public);

ILGenerator ctor1IL = ctor1.GetILGenerator();
ctor1IL.Emit(OpCodes.Ldarg_0);

//get base constructor
var bc = tb.BaseType.GetConstructor(System.Type.EmptyTypes);
ctor1IL.Emit(OpCodes.Call, bc);  
ctor1IL.Emit(OpCodes.Ldarg_0);
ctor1IL.Emit(OpCodes.Ldstr, typeSignature);
ctor1IL.Emit(OpCodes.Stfld, fbname);
ctor1IL.Emit(OpCodes.Ret);
Was dit nuttig?

Oplossing

The field name already exists in the base class.

This sounds like you already have the field name in the base class. If that's the case, what your code does is to create another field called name in the derived class. You then write to that field, not to the one in the base class.

What you should do is something like:

FieldInfo nameField = tb.BaseType.GetField("name");

…

ctor1IL.Emit(OpCodes.Stfld, nameField);
Gelisensieer onder: CC-BY-SA met toeskrywing
Nie verbonde aan StackOverflow
scroll top