我们有一个WCF服务,其中包括在服务的根级具有DataContract和DataMember的合同中的Serializable类。
在尝试构建解决问题的解决方案时,我遇到了以下情况:
[ServiceContract]
public interface IService1
{
[OperationContract]
CompositeType GetDataUsingDataContract();
}
[DataContract]
public class CompositeType
{
[DataMember]
public MyType MyProperty { get; set; }
}
[Serializable]
public class MyType
{
private int amount1;
[XmlElement(Form = XmlSchemaForm.Unqualified, DataType = "int", ElementName = "AmountN")]
public int Amount1
{
get
{ return amount1; }
set
{ amount1 = value; }
}
}
提供以下xsd:
<xs:complexType name="CompositeType">
<xs:sequence>
<xs:element name="MyProperty" type="tns:MyType" nillable="true" minOccurs="0"/>
</xs:sequence>
</xs:complexType><xs:element name="CompositeType" type="tns:CompositeType" nillable="true"/>
<xs:complexType name="MyType">
<xs:sequence>
<xs:element name="amount1" type="xs:int"/>
</xs:sequence>
</xs:complexType>
<xs:element name="MyType" type="tns:MyType" nillable="true"/>
</xs:schema>
问题是:为什么私人而非公众成员被序列化?
答案 0 :(得分:1)
This msdn article可以解释为什么wcf能够序列化你的MyType:
数据协定序列化程序支持的类型:。 。
使用SerializableAttribute属性标记的类型。很多类型 包含在.NET Framework基类库中的内容属于此 类别。 DataContractSerializer完全支持此序列化 .NET Framework远程处理使用的编程模型 BinaryFormatter和SoapFormatter,包括支持 ISerializable接口。
由于wcf序列化私有字段没有问题,可能这就是将privet字段amount1
序列化的原因。
INO,问题是“为什么你的属性Amount1没有序列化?”我试图重命名它(与字段名称不同),删除它上面的xml属性,然后重试
答案 1 :(得分:1)
序列化程序和序列化属性是两回事。
XmlElement
是XmlSerializer
的属性,但对DataContractSerializer
或BinaryFormatter
没有意义。 XmlElementAttribute Class
DataContractSerializer
可以序列化多种类型,但它使用自己的序列化算法Link。序列化标有[Serializable]
的对象时,
DataContractSerializer
遵循默认序列化模式(序列化所有成员,[NonSerialized]
适用)。如果需要更多控制,那么可以实现ISerializable
进行自定义序列化,然后可以在序列化对象Serialization 中设置节点名称和值。
还可以选择实现IXmlSerializable
并完全控制序列化对象的外观。