Reputation: 491
I tried to find the answer on the Internet, but without success. Instead, several times in different posts I've met the phrase that “private fields … will never be serialized”. So I guess this is not a bug but a philosophy.
I do not understand this, however. How can a class be serialized and then restored back without the private members responsible for the class's internal logic?
Upvotes: 0
Views: 817
Reputation: 12469
The reason why YamlDotNet serializes only public properties by default is because doing otherwise would break encapsulation. Accessing private members would mean that the model would be unable to guarantee its invariants. If you compare with other libraries, such as Json.NET, you will notice that they use the same approach.
I don't think that this is a problem because you should not be (de)serializing your domain model directly. Doing so would constrain your domain model to your serialization schema, which in many cases will need to be different. That's the same problem as trying to map your domain model to a relational database.
Instead, you should define a serialization model and map between your domain model and that serialization model. In that case there's no need to serialize private fields.
That said, if you really want to serialize private fields, that's trivial to do. You need
register you own implementation of ITypeInspector
that returns private fields. You can base your implementation on ReadableFieldsTypeInspector
.
Upvotes: 1