English 中文(简体)
在DataContractSerializer读取的XML中,顺序是否重要?
原标题:Does Order Matter in the XML Read by the 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中它被正确反序列化。为什么?

最佳回答

因为顺序很重要。除非您在数据成员属性中指定顺序,否则将使用字母顺序。

这在这篇MSDN文章中有所解释。

一般来说,总是明确指定您的DataMember属性上的Order是一个好的实践:

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

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

暂无回答




相关问题
Test "User Must Change Password" field in .Net 3.5

I m trying to perform some basic AD User managment tasks in C# using .Net 3.5 I ve got a System.DirectoryServices.AccountManagement.UserPrincipal object that contains the user details. I can call ...

Entity Framework - Many to many question

I have a table called ASB and a table called PeopleInvolved. There is a junction table called PeopleInvolved_ASB which simply contains an ASBID and a PeopleInvolvedID column. The columns act as a ...

WCF: DuplexChannelFactory timeout error

I m using a DuplexChannelFactory when accessing my WCF service so that my service can use a callBackChannel to communicate back to the client. That s all fine but I get a timeout error when creating ...

AutoResetEvent, ManualResetEvent vs Monitor

Lets say I have to orchestrate a synchronization algorithm in .Net 3.5 SP1 and any of the synchronization primitives listed in the title fit perfectly for the task. From a performance perspective, is ...

Managing multiple .Net-Frameworks on a webserver

So I m in charge to deploy my project on the productive server where some other ASP.NET-Websites are also set up. The problem now is that I wrote my whole project under .NET 3.5 but on the webserver ...

Unit Testing .NET 3.5 projects using MStest in VS2010

There s a bug/feature in Visual Studio 2010 where you can t create a unit test project with the 2.0 CLR. https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=483891&wa=...

热门标签