0

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

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 为空-我在这里缺少什么?

4

1 回答 1

2

查看的文档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);
于 2015-02-04T16:13:21.460 回答