2015-11-12 3 views
1

В C#, мы можем создать частную собственность выполнив:Как создать частную собственность с помощью PropertyBuilder

private string Name { get; set; } 

Однако предположим, что мы создаем свойство, используя Reflection.Emit.PropertyBuilder.

Следующий код создает общественного свойства (методы получения и установки еще не определены):

PropertyBuilder prop = typeBuilder.DefineProperty("Name", PropertyAttributes.None, CallingConvention.HasThis, typeof(string), Type.EmptyTypes); 

Как будет определять это же свойство, но с частной видимости?

Reflection.Emit.FieldBuilder может быть указан FieldAttributes.Private, но PropertyBuilder, похоже, не предлагает нечто подобное.

Возможно ли это с Reflection.Emit?

ответ

3

При создании свойств вы можете установить частные свойства get/set, как показано ниже. Вы не можете установить свойство как личное.

От 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); 
Смежные вопросы