如何使用 PropertyBuilder 创建私有属性 [英] How to create a private property using PropertyBuilder
问题描述
在 C# 中,我们可以通过以下方式创建私有属性:
In C#, we can create a private property by doing:
private string Name { get; set; }
但是,假设我们正在使用 Reflection.Emit.PropertyBuilder.
However, suppose we are creating a property using Reflection.Emit.PropertyBuilder.
以下代码将创建一个public 属性(尚未定义 getter 和 setter 方法):
The following code will create a public property (getter and setter methods not yet defined):
PropertyBuilder prop = typeBuilder.DefineProperty("Name", PropertyAttributes.None, CallingConvention.HasThis, typeof(string), Type.EmptyTypes);
如何定义相同的属性但具有私有可见性?
How will I define this same property but with private visibility?
Reflection.Emit.FieldBuilder 可以指定为 FieldAttributes.Private
,但 PropertyBuilder
似乎没有提供类似的东西.
Reflection.Emit.FieldBuilder can be specified a FieldAttributes.Private
, but PropertyBuilder
does not seem to offer something similar.
这可以通过 Reflection.Emit 实现吗?
Is this possible with Reflection.Emit?
推荐答案
在构建属性时,您可以设置私有的 get/set 属性,如下所示.您不能将属性本身设置为私有.
When building properties you can set private get / set properties as shown below. You cannot set the Property itself as private.
从文档,相关代码如下所示.
From the documentation, the relevant code is shown below.
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);
这篇关于如何使用 PropertyBuilder 创建私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!