在C#中,我们可以通过以下操作创建私有属性:
private string Name { get; set; }
但是,假设我们正在使用Reflection.Emit.PropertyBuilder.创建属性
以下代码将创建public属性(尚未定义getter和setter方法):
PropertyBuilder prop = typeBuilder.DefineProperty("Name", PropertyAttributes.None, CallingConvention.HasThis, typeof(string), Type.EmptyTypes);
如果private可见,我将如何定义相同的属性?
Reflection.Emit.FieldBuilder可以指定为FieldAttributes.Private
,但PropertyBuilder
似乎没有提供类似的功能。
反射发射可以做到这一点吗?
构建属性时,您可以设置私有的get/set属性,如下所示。不能将属性本身设置为私有。
从文档中,相关代码如下所示。
PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty("CustomerName",
PropertyAttributes.HasDefault,
typeof(string),
null);
// The property set and property get methods require a special
// set of attributes.
MethodAttributes getSetAttr =
MethodAttributes.Public | MethodAttributes.SpecialName |
MethodAttributes.HideBySig;
// Define the "get" accessor method for CustomerName.
MethodBuilder custNameGetPropMthdBldr =
myTypeBuilder.DefineMethod("get_CustomerName",
getSetAttr,
typeof(string),
Type.EmptyTypes);
ILGenerator custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();
custNameGetIL.Emit(OpCodes.Ldarg_0);
custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
custNameGetIL.Emit(OpCodes.Ret);
// Define the "set" accessor method for CustomerName.
MethodBuilder custNameSetPropMthdBldr =
myTypeBuilder.DefineMethod("set_CustomerName",
getSetAttr,
null,
new Type[] { typeof(string) });
ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();
custNameSetIL.Emit(OpCodes.Ldarg_0);
custNameSetIL.Emit(OpCodes.Ldarg_1);
custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
custNameSetIL.Emit(OpCodes.Ret);
// Last, we must map the two methods created above to our PropertyBuilder to
// their corresponding behaviors, "get" and "set" respectively.
custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);