【问题标题】:Why is the public property not being serialized?为什么公共财产没有被序列化?
【发布时间】:2013-04-18 11:37:11
【问题描述】:

我们有一个 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>

问题是:为什么私有成员而不是公共成员被序列化?

【问题讨论】:

标签: wcf serialization xsd


【解决方案1】:

序列化器和序列化属性是两个不同的东西。

XmlElementXmlSerializer 的属性,但对于 DataContractSerializerBinaryFormatter 没有任何意义。 XmlElementAttribute Class

DataContractSerializer可以序列化多种类型,但是它使用了自己的序列化算法Link。序列化标有[Serializable] 的对象时, DataContractSerializer 遵循默认序列化模式(序列化所有成员,[NonSerialized] 适用)。如果您需要更多控制,则可以实现ISerializable 进行自定义序列化,然后您可以在序列化对象Serialization 中设置节点名称和值。

还有一个选项可以实现IXmlSerializable 并完全控制序列化对象的外观。

【讨论】:

    【解决方案2】:

    This msdn article 可以解释一下,为什么 wcf 能够序列化你的 MyType:

    数据协定序列化程序支持的类型:. . .

    用 SerializableAttribute 属性标记的类型。多种类型 包含在 .NET Framework 基类库中属于此 类别。 DataContractSerializer 完全支持这种序列化 .NET Framework 远程处理使用的编程模型, BinaryFormatter 和 SoapFormatter,包括对 ISerializable 接口。

    而且由于wcf序列化私有字段没有问题,可能这就是序列化你的privet字段amount1的原因。

    INO,问题是“为什么你的属性 Amount1 没有序列化?”我会尝试重命名它(与字段名称不同),删除其上的 xml 属性,然后重试.

    【讨论】:

    • 很抱歉删除了接受,我已根据您的建议更改了名称,并添加了赏金。
    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2018-05-18
    • 2011-12-21
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多