vendredi 8 novembre 2019

Setting property with private setter using reflection

When I try to set the value of a property that has a private setter through reflection, I am able to successfully modify the value of the property.

In the code snippet below, the value of Setting1 modifies to "Hello" after the SetValues call.

Can anyone provide insight into how can a properties value be modified when the setter is private. Thank you.

public class SettingsClass
{
    public string Setting1 { get;  private set; }
}

public class ReflectionClass
{
    public static void SetValues(SettingsClass settingsClassObj, string paramVal)
    {
        var configObj = serviceContext.CodePackageActivationContext.GetConfigurationPackageObject(configName);

        var settingsObjType = settingsClassObj.GetType();
        var properties = settingsObjType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach(var property in properties)
        {
            property.SetValue(settingsClassObj, paramVal, null);
        }
    }
}

SettingsClass settingObj = new SettingsClass();
ReflectionClass.SetValues(settingObj, "Hello");




Aucun commentaire:

Enregistrer un commentaire