I wrote a custom serializer that works by setting object properties by reflection. Serializable classes are tagged with serializable attribute and all serializable properties are also tagged. For example, the following class is serializable:
[Serializable]
public class Foo
{
[SerializableProperty]
public string SomethingSerializable {get; set;}
public string SometthingNotSerializable {get; set;}
}
SomethingSerializable
PropertyInfo propertyInfo; //the property info of the property to set
//...//
if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
{
propertyInfo.GetSetMethod().Invoke(obj, new object[]{val});
}
public string SomethingSerializable {get; private set;}
propertyInfo.GetSetMethod()
As you already figured out, one way to access a non-public setter is as follows:
PropertyInfo property = typeof(Type).GetProperty("Property");
property.GetSetMethod(true).Invoke(obj, new object[] { value });
There is another way, though, if I recall correctly:
PropertyInfo property = typeof(Type).GetProperty("Property");
property.SetValue(obj, value, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null);