XML中的Order Order是否由DataContractSerializer读取?

时间:2010-02-12 06:45:39

标签: wcf .net-3.5 serialization datacontractserializer

我有以下代码:

[DataContract(Namespace = "")]
public class User
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string FullName { get; set; }
}

//Deserialization test
public void Test()
{

  //CASE 1.
  //string xml = "<User><UserName>john</UserName>" + 
  //                    "<FullName>John Lennon</FullName></User>";

  //CASE 2.
  string xml = "<User><FullName>John Lennon</FullName>" + 
                      "<UserName>john</UserName></User>";


  byte[] byteArray = Encoding.UTF8.GetBytes(xml);
  User user = null;
  using (MemoryStream stream = new MemoryStream(byteArray))
  {
    DataContractSerializer serializer = 
           new DataContractSerializer(typeof(User), "User", "");
    user = (User)serializer.ReadObject(stream);
  }
}

在案例1中,FullName属性未反序列化,但在案例2中,它被正确反序列化。为什么呢?

1 个答案:

答案 0 :(得分:9)

因为订单很重要。除非您在DataMember属性中指定顺序,否则将使用字母顺序。

this MSDN article中解释了这一点。

通常,始终在DataMember属性上明确指定Order是一个好习惯:

[DataMember(IsRequired=true, Order=0)]
public string FullName { get; set; }

[DataMember(IsRequired=true, Order=1)]
public string UserName { get; set; }