如何使用 PropertyBuilder 创建私有 属性

How to create a private property using PropertyBuilder

在 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 似乎没有提供类似的东西。

Reflection.Emit可以吗?

构建属性时,您可以设置私有获取/设置属性,如下所示。您不能将 属性 本身设置为私有。

来自the documentation,相关代码如下所示

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