我有如下代码:
[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它被反序列化正确.为什么?
因为顺序很重要使用字母顺序,除非您在DataMember属性中指定顺序.
原文链接:https://www.f2er.com/xml/292239.html这在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; }