简体   繁体   中英

C# Dynamic assembly Can't create new object and load to field

I am trying to create new object for given type and load it to the field, but it throws an

InvalidProgramException.

Doing same using locals works. Maybe doing something wrong with fields? This does not work:

MethodAttributes getSetAttr = MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
FieldBuilder propNameBldr = typeBuilder.DefineField("_" + PropName, PropType, FieldAttributes.Private);
propNamePropBldr = typeBuilder.DefineProperty(PropName, PropertyAttributes.HasDefault, PropType, null);
propNameGetPropMthdBldr = typeBuilder.DefineMethod("get_" + PropName, getSetAttr, PropType, Type.EmptyTypes);
ConstructorInfo baseCtor = basePropType.GetConstructor(new Type[] { });

ILGenerator propNameGetIL = propNameGetPropMthdBldr.GetILGenerator();

propNameGetIL.Emit(OpCodes.Newobj, baseCtor);
propNameGetIL.Emit(OpCodes.Stfld, PropNameBldr);

propNameGetIL.Emit(OpCodes.Ldfld, PropNameBldr);
propNameGetIL.Emit(OpCodes.Ret);
propNamePropBldr.SetGetMethod(propNameGetPropMthdBldr);

But this works:

MethodAttributes getSetAttr = MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
FieldBuilder propNameBldr = typeBuilder.DefineField("_" + PropName, PropType, FieldAttributes.Private);
propNamePropBldr = typeBuilder.DefineProperty(PropName, PropertyAttributes.HasDefault, PropType, null);
propNameGetPropMthdBldr = typeBuilder.DefineMethod("get_" + PropName, getSetAttr, PropType, Type.EmptyTypes);
ConstructorInfo baseCtor = basePropType.GetConstructor(new Type[] { });

ILGenerator propNameGetIL = propNameGetPropMthdBldr.GetILGenerator();
LocalBuilder lc = propNameGetIL.DeclareLocal(PropType);
propNameGetIL.Emit(OpCodes.Newobj, baseCtor);
propNameGetIL.Emit(OpCodes.Stloc, PropNameBldr);

propNameGetIL.Emit(OpCodes.Ldloc, PropNameBldr);
propNameGetIL.Emit(OpCodes.Ret);
propNamePropBldr.SetGetMethod(propNameGetPropMthdBldr);

So what is the difference and why first not working? Thanks.

Non-static fields need an object reference.

A better way to generate IL is to use expression trees.

Also, you can answer all such questions yourself by writing the equivalent code in C# and decompiling the compiler output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM