发出并设置属性

时间:2015-02-04 15:58:23

标签: c# emit

我想发布一个属性并设置它:

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);

但是pb.SetMethod在那时是空的 - 我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

查看the documentation for DefineProperty,您仍然需要自己定义setter(和getter)方法。这是与set方法相关的部分,但您可能也需要执行get方法:

// 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);
相关问题