BinaryFormatter.Deserialize HeaderHandler Header Capture Return Value

I am using BinaryFormatter.Deserialize(Stream, HeaderHandler). I might have missed something obvious, but I can’t find examples on the Internet, so I hope someone can shed some light. I passed in my delegate HeaderHandler, which returns an object, but I do not know how to get this object, which it returns?

+4
source share
2 answers

TO; tracked through a reflector. The only time a regular implementation uses this value is when processing some data through remote access, if the value returned from the HeaderHandler is MarshalByRefObject , in which case the identification is obtained and used to bind. Specifically, the constructor of System.Runtime.Remoting.Messaging.MethodCall .

But all this is an implementation detail! In most reasonable scenarios, the answer is this: it is not used.

In fact, the header processing has after the main deserialization, which blatantly violates the use of the header handler to set some values ​​of the context object, which you then process.

However, your header handler can update local variables:

 string someValue = null; object obj = serializer.Deserialize(source, headers => { // check the headers and assign someValue based on // what you find there; for brevity, make it up! someValue = "something from the headers"; return null; }); Console.WriteLine(someValue); 

Must love full lexical closures.

Personally, however, I conclude: this is not a way to do this. I would just pass the DTO with exactly the data you want to send.

+3
source

As far as I can tell, BinaryFormatter does nothing with the returned object.

 var deserializedObject = (TypeOfDeserializedObject) BinaryFormatter.Deserialize(stream, headers => { //do stuff with your headers here foreach (var header in headers) { } return new object(); }); 
0
source

Source: https://habr.com/ru/post/1403880/


All Articles