我试图将一些数据传递给DataContractSerializer的StreamingContext,但我无法弄清楚如何。 以下是我的代码的一小部分示例:
MemoryStream stream = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(OldClass));
serializer.WriteObject(stream, _OldClass);
stream.Seek(0, SeekOrigin.Begin);
serializer = new DataContractSerializer(typeof(NewClass));
//here I would like to give the serializer e.g. a string as StreamingContext.Context
_NewClass = (NewClass)serializer.ReadObject(stream);
答案 0 :(得分:6)
你不能。
使用DataContractSerializer
时,传递给序列化/反序列化回调的StreamingContext
实例来自内部XmlObjectSerializerContext
。
此处的初始化代码:
internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
: this(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(StreamingContextStates.All), serializer.IgnoreExtensionDataObject, dataContractResolver)
{
// ...
}
如您所见,此代码会创建new StreamingContext(StreamingContextStates.All)
为了清楚起见,NetDataContractSerializer
的类似代码使用了来自传递的序列化程序实例的上下文:
internal XmlObjectSerializerContext(NetDataContractSerializer serializer)
: this(serializer, serializer.MaxItemsInObjectGraph, serializer.Context, serializer.IgnoreExtensionDataObject)
{
}