在应用程序中,我有以下接口/实现结构:
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; }
}
..它运作良好&#39;就像在 - datacontractserializer确实创建
<MyInterfaceImplementation>...</MyInterfaceImplementation>
...节点而不是z:anyType但是我不想/不能改变我的接口&#39;属性。在这种情况下,有没有办法控制或帮助数据合同序列化器?