简体   繁体   中英

Emit and set Property

I would like to Emit a Property and set it:

var pb = tb.DefineProperty("myProp", PropertyAttributes.None, typeof(object), Type.EmptyTypes);
IL.Emit(OpCodes.Newobj, typeof(object).GetConstructor(Type.EmptyTypes));
IL.Emit(OpCodes.Call, pb.SetMethod);

but the pb.SetMethod is null at that point - what am I missing here?

Looking at the documentation for DefineProperty , you still need to define the setter (and getter) methods yourself. This is the part relevant to a set method, but you'll probably need to do the get method too:

// Backing field
FieldBuilder customerNameBldr = myTypeBuilder.DefineField(
    "customerName",
    typeof(string),
    FieldAttributes.Private);

// Property
PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty(
    "CustomerName",
    PropertyAttributes.HasDefault,
    typeof(string),
    null);

// Attributes for the set method.
MethodAttributes getSetAttr = MethodAttributes.Public |
                              MethodAttributes.SpecialName |
                              MethodAttributes.HideBySig;

// Set method
MethodBuilder custNameSetPropMthdBldr = myTypeBuilder.DefineMethod(
    "set_CustomerName",
    getSetAttr,     
    null,
    new Type[] { typeof(string) });

ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();

// Content of the set method
custNameSetIL.Emit(OpCodes.Ldarg_0);
custNameSetIL.Emit(OpCodes.Ldarg_1);
custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
custNameSetIL.Emit(OpCodes.Ret);

// Apply the set method to the property.
custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);

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