c# - How can I call the constructor before deserialisation? -


i try serialize , deserialize custom class via data contract serialization. serialization works great. however, when deserializing, run problem, because of (source):

constructors not called when objects deserialized.

the thing bit of initialisation in constructor. includes data structures.

without call constructor, data structures null , calls setter functions during deserialisation fail.

how can call constructor or initialize object before or during deserialisation process, before accessor used?

there few methods can declare callbacks via attributes, (same source):

// method called after object  // deserialized. use instead of // constructror. [ondeserialized]  void ondeserialized(streamingcontext context) {     fullname = firstname + " " + lastname; } 

but looks triggered after deserialisation.

do have switch xml serialization?

create constructor signature

protected yourclassname(serializationinfo info, streamingcontext context) { } 

and have class implement iserializable. on serialization calls iserializable.getobjectdata() on de-serialization calls above constructor.

see custom serialization: implementing iserializable interface on msdn

if don't need work in constructor can use attribute [ondeserializing] instead of [ondeserialized] work done before deserialization instead of after.

[ondeserializing] private void setvaluesondeserializing(streamingcontext context) {     // code not shown. } 

note: if have more 1 [ondeserializing] method in object graph order called in not dertimistic.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -