0

我有这个类由 Web 服务提供,然后由 Silverlight 应用程序使用(我不知道这是否相关)

[Serializable]
public class Entry
{
    private string _title;

    public string Id { get; set; }
    public string Title { get { return _title; } set { _title = value; } }
    public string Link { get; set; }
    public DateTime Published { get; set; }
    public DateTime Updated { get; set; }
    public User User { get; set; }
    public Service Service { get; set; }
    public List<Comment> Comments { get; set; }
    public List<Like> Likes { get; set; }
    public List<Media> Media { get; set; }
}

我添加的_title变量来演示出了什么问题。当我在 silverlight 应用程序中引用 Web 服务时,它会生成以下 xsd:

  <xs:complexType name="Entry">
    <xs:sequence>
      <xs:element name="_title" nillable="true" type="xs:string" />
      <xs:element name="_x003C_Comments_x003E_k__BackingField" nillable="true" type="tns:ArrayOfComment" />
      <xs:element name="_x003C_Id_x003E_k__BackingField" nillable="true" type="xs:string" />
      <xs:element name="_x003C_Likes_x003E_k__BackingField" nillable="true" type="tns:ArrayOfLike" />
      <xs:element name="_x003C_Link_x003E_k__BackingField" nillable="true" type="xs:string" />
      <xs:element name="_x003C_Media_x003E_k__BackingField" nillable="true" type="tns:ArrayOfMedia" />
      <xs:element name="_x003C_Published_x003E_k__BackingField" type="xs:dateTime" />
      <xs:element name="_x003C_Service_x003E_k__BackingField" nillable="true" type="tns:Service" />
      <xs:element name="_x003C_Updated_x003E_k__BackingField" type="xs:dateTime" />
      <xs:element name="_x003C_User_x003E_k__BackingField" nillable="true" type="tns:User" />
    </xs:sequence>
  </xs:complexType>

请注意,只有 title 属性被简单命名,其他属性<Link>_BackingField在您尝试加载元素时完全消失,因为您不能在属性名称中包含 < 或 >。

为什么它序列化支持字段而不是公共属性?

4

2 回答 2

3

本文所述,当您将DataContractSerializer(WCF 的默认序列化程序)与Serializable属性结合使用时,行为是所有字段(公共和私有)都被序列化。因为在您的情况下支持字段是自动生成的,所以编译器会提供有趣的名称,这些名称不会与您可能创建的任何字段名称冲突(C# 可能不接受标识符中的“<”或“>”,但 CLR没那么挑剔)。

纠正这种情况的最简单方法可能是根据需要向类添加DataContractDataMember属性Entry

于 2009-05-04T15:11:10.007 回答
1

不要使用自动属性。而不是写:

public string Id { get; set; }

写:

string id;
public string Id { get { return id;} set {id = value;} }

在自动属性的情况下,只有支持字段会被序列化,这就是为什么你会得到奇怪的名字。

于 2009-05-04T15:09:50.353 回答