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