我正在序列化和反序列化可能会或可能不会使用已知类型标记的类对象。因此,我创建了自己的DataContractResolver来处理在引用的程序集中找到的加载知识类型。我一直难以理解为什么WriteObject(stream,object)不使用DataContractSerialization构造函数中设置的DataResolver。在查看DataContractSerialization WriteObject方法时,它似乎为您实例化了一个XmlDictionaryWriter:
public virtual void WriteObject(Stream stream, object graph)
{
XmlObjectSerializer.CheckNull(stream, "stream");
XmlDictionaryWriter xmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false);
this.WriteObject(xmlDictionaryWriter, graph);
xmlDictionaryWriter.Flush();
}
但是它似乎将Resovler设置为null而不是检查Resolver。
internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph)
{
this.WriteObjectHandleExceptions(writer, graph, null);
}
我对小组的问题是,这似乎是一个错误还是设计错误。如果按设计,有关使用派生DataResolver的最佳方法的任何想法?您可以在构造中设置Resolver,但并不总是使用它,这似乎令人困惑。
我嘲笑了一个快速示例,以显示我在代码中如何使用它。很遗憾,我无法提交我的代码供公众审核。谢谢你的帮助。
using System;
using System.IO;
using System.Runtime.Serialization;
class Program
{
static void Main(string[] args)
{
DummyClass dummyclass = new DummyClass { MyString = "MyString", One = 1 };
DataContractSerializerSettings settings = new DataContractSerializerSettings { DataContractResolver = new MyResolver() };
string serializedobject = String.Empty;
using (MemoryStream memorystream = new MemoryStream())
using (StreamReader reader = new StreamReader(memorystream))
{
DataContractSerializer serializer = new DataContractSerializer(dummyclass.GetType(), settings);
//This does not call the Resolver set in the constructor
serializer.WriteObject(memorystream, dummyclass);
memorystream.Position = 0;
serializedobject = reader.ReadToEnd();
}
Console.WriteLine(serializedobject);
Console.ReadLine();
}
}
public class MyResolver : DataContractResolver
{
public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
{
return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null) ?? Type.GetType(typeName + ", " + typeNamespace);
}
public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString typeName, out System.Xml.XmlDictionaryString typeNamespace)
{
//This does not get called
return knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace);
}
}
public class DummyClass
{
public int One { get; set; }
public string MyString { get; set; }
}