发出并设置 属性

Emit and set Property

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

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 在那一点上是空的 - 我在这里错过了什么?

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