The streamingcontext type appears in many serialization methods. Getobjectdata of iserializable and special Constructor (used for deserialization ). There are also [ondeserialized], [ondeserializing], [onserialized], [onserializing] feature flag methods. And the getobjectdata and setobjectdata methods of getrealobject and iserializationsurrogate of iobjectreference.
Streamingcontext indicates the data location difference between the two ends during serialization (or rice serialization. Based on these differences, the entire serialization or deserialization process can be adjusted independently.
The state attribute of streamingcontext is the streamingcontextstates enumeration (with the flags feature), which represents the location of the serialization source and destination. The default value is streamingcontextstates. all, representing all other values (more about streamingcontextstates: http://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.streamingcontextstates ). The context attribute is a user-defined object.
You can set streamingcontext Of The formatter by using the iformatter. Context attribute. (Common binaryformatter inherits iformatter)
Code to simulate serialization and deserialization of an object in different processes. (Use streamingcontextstates. crossprocess ):
Using system;
Using system. diagnostics;
Using system. IO;
Using system. runtime. serialization;
Using system. runtime. serialization. formatters. Binary;
Namespace mgen
{
[Serializable]
Class A: iserializable
{
// Serialization
Public void getobjectdata (serializationinfo info, streamingcontext context)
{
If (context. State & streamingcontextstates. crossprocess) = streamingcontextstates. crossprocess)
Info. addvalue ("_ process", (string) Context. context );
}
// Public Constructor
Public (){}
// Deserialization
Protected A (serializationinfo info, streamingcontext context)
{
If (context. State & streamingcontextstates. crossprocess) = streamingcontextstates. crossprocess)
Console. writeline ("source process:" + info. getstring ("_ Process "));
}
}
Class Program
{
Static void main ()
{
Using (var ms = new memorystream ())
{
// Create streamingcontext
VaR context = new streamingcontext (streamingcontextstates. crossprocess, process. getcurrentprocess (). processname );
// Set iformatter. Context
VaR bf1 = new binaryformatter (null, context );
// Serialization
Bf1.serialize (MS, new ());
// Assume deserialization in another process
Ms. Seek (0, seekorigin. Begin );
VaR bf2 = new binaryformatter ();
Bf2.deserialize (MS );
}
}
}
}
Output:
Source Process: mgen
When the program outputs the serialization, streamingcontextstates is set to crossprocess and stored in streamingcontext. Context (that is, the process name in the source serialization operation) in serializationinfo ).