How to create a private property using PropertyBui

2019-08-10 16:58发布

问题:

In C#, we can create a private property by doing:

private string Name { get; set; }

However, suppose we are creating a property using Reflection.Emit.PropertyBuilder.

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 can be specified a FieldAttributes.Private, but PropertyBuilder does not seem to offer something similar.

Is this possible with Reflection.Emit?

回答1:

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