我正在尝试将一些数据传递到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);
最佳答案
你不能
使用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)
{
}