在一个应用程序中,我有以下接口/实现结构:
public interface IMyInterface
{
IMyOtherInterface InstanceOfMyOtherInterface { get; }
}
public interface IMyOtherInterface
{
string SomeValue { get; }
}
[DataContract(Name = "MyInterfaceImplementation", Namespace = "")]
public class MyInterfaceImplementation : IMyInterface
{
[DataMember(EmitDefaultValue = false), XmlAttribute(Namespace = "")]
public IMyOtherInterface InstanceOfMyOtherInterface { get; private set; }
public MyInterfaceImplementation()
{
this.InstanceOfMyOtherInterface = new MyOtherInterfaceImplementation("Hello World");
}
}
[DataContract(Name = "MyOtherInterfaceImplementation", Namespace = "")]
public class MyOtherInterfaceImplementation : IMyOtherInterface
{
[DataMember]
public string SomeValue { get; private set; }
public MyOtherInterfaceImplementation(string value)
{
this.SomeValue = value;
}
}
现在,每当我使用 .Net DataContractSerializer 将其序列化(在我的情况下为字符串)时,如下所示:
var dataContractSerializer = new DataContractSerializer(typeof(MyInterfaceImplementation));
var stringBuilder = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(stringBuilder, new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 }))
{
dataContractSerializer.WriteObject(xmlWriter, this);
}
var stringValue = stringBuilder.ToString();
生成的 xml 看起来很像这样:
<?xml version="1.0" encoding="utf-16"?>
<z:anyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="MyInterfaceImplementation" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<InstanceOfMyOtherInterface xmlns="" i:type="InstanceOfMyOtherInterface">
<SomeValue>Hello World</SomeValue>
</InstanceOfMyOtherInterface>
</z:anyType>
这些 *anyType* 似乎来自 datacontractserializer 将 MyInterfaceImplementation 实例序列化为 System.Object,同样具有其他接口属性。
如果我在接口及其实现中使用了具体类型,如下所示:
public interface IMyInterface
{
MyOtherInterface InstanceOfMyOtherInterface { get; }
}
..它工作得“很好” - datacontractserializer 确实创建
<MyInterfaceImplementation>...</MyInterfaceImplementation>
...节点而不是 z:anyType 节点,但我不想/不能更改我的接口的属性。在这种情况下,有什么方法可以控制或帮助数据合同序列化程序?