【发布时间】:2014-07-17 02:35:59
【问题描述】:
根据 MSDN,构造函数的第一个参数 DataContractJsonSerializer(Type, IEnumerable<Type>) 被定义为被序列化或反序列化的实例的类型。
然而,我最近在一些产品代码中遇到了一个错误,但很快意识到序列化按预期工作。一个简化的版本是:
var knownTypes = new[] { typeof(TypeA), typeof(TypeB) };
// Bug below. Should be 'otherType = typeof(C)'
// Always sets otherType to System.RuntimeType
var otherType = typeof(TypeC).GetType();
var serializer = new DataContractJsonSerializer(otherType, knownTypes);
using(var output = new MemoryStream())
{
serializer.WriteObject(output, new TypeA());
output.Position = 0;
var copy = (TypeA) serializer.ReadObject(output);
}
这是因为序列化程序将成功写入具有type 参数或knownTypes 参数中指定的类型的任何对象。
我的问题是:
如果序列化程序可以正确写入任一参数中指定的类型的对象,那么使用第一个参数的目的是什么?
是否存在第一个参数被不同处理或对序列化程序有特殊用途的特殊情况?
【问题讨论】:
标签: c# serialization