Let's say I have this class :
[XmlType]
public class TestModel : BindableBase
{
private int _id;
[XmlElement(Order = 7)]
public int Id
{
get
{
return _id;
}
set
{
SetProperty(ref _id, value);
}
}
}
I am doing a lot of serialization and deserialization (from/to Json with newtonsoft and from/to byte arrays with protobuf) and I would like to avoid calling the SetProperty
method when setting the property during the deserialization.
Basically I would like to have something along the line with:
[XmlElement(Order = 7)]
public int Id
{
get
{
return _id;
}
set
{
if(!serializing)
SetProperty(ref _id, value);
else
_id = value;
}
}
The reason I want to do this is because first I don't need the event OnPropertyChanged
to be raised during deserialization and secondly because it is costly in terms of performance.
I tried using the OnDeserializing
and OnDeserialized
to set a flag but while OnDeserialized
lets me know when the deserialization is over, methods decorated with OnDeserializing
are not called just before the deserialization but during the operation.
This code is in a Portable Class Library assembly so I cannot use SerializationContext
.
Any clues/hints are welcome!
Simplest thing that comes into my mind is to use a parametrized constructor all over your code, which sets the "serializing" flag to false, and set the "serializing" flag to true in the parameterless constructor. Instead of the first one, you can use a Factory which will use the parameterless constructor also, but will set the flag appropriately after creation.