Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

serialization - How do I deserialize into an existing object - C#

In C#, after serializing an object to a file how would I deserialize the file back into an existing object without creating a new object?

All the examples I can find for custom serialization involve implementing a constructor that will be called upon deserialization which is exactly what I want except that I don't want the function to be a constructor.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some serializers support callbacks; for example, both BinaryFormatter and DataContractSerializer (and protobuf-net, below) allow you to specify a before-serializaton callback, and since they skip the constructor, this may well be enough to initialize the object. The serializer is still creating it, though.


Most serializers are fussy about wanting to create the new object themselves, however some will allow you to deserialize into an existing object. Well, actually the only one that leaps to mind is protobuf-net (disclosure: I'm the author)...

This has 2 different features that might help here; for the root object (i.e. the outermost object in a graph) you can supply the existing object directly to either the Merge methods (in v1, also present in v2 for compatibility), or (in v2) the Deserialize methods; for example:

var obj = Serializer.Merge<YourType>(source, instance);

However, in a larger graph, you might want to supply other objects yourself (than just the root). The following is not exposed on the attribute API, but is a new feature in v2:

RuntimeTypeModel.Default[typeof(SomeType)].SetFactory(factoryMethod);

where factoryMethod can be either the name of a static method in SomeType (that returns a SomeType instance), or can be a MethodInfo to any static method anywhere. The method can additionally (optionally) take the serialization-context as a parameter if you want. This method should then be used to supply all new instances of SomeType.


Note: protobuf-net is not quite the same as BinaryFormatter; for best effect, you need to tell it how to map your members - very similar to marking things as [DataMember] for WCF/DataContractSerializer. This can be attributes, but does not need to be.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...