简体   繁体   English

为什么XMLSerializer使用基类的DefaultValue属性进行序列化

[英]Why does XMLSerializer take DefaultValue Attribute of base class to serialize

using System.ComponentModel;
using System.IO;
using System.Xml.Serialization;

namespace SerializerTest {
    static class Program {
        static void Main() {
            using (TextWriter textWriter = new StreamWriter("data.xml")) {
                Data data = new Data();
                new XmlSerializer(typeof(Data)).Serialize(textWriter, data);
                textWriter.Close();
            }
            using (TextWriter textWriter = new StreamWriter("exData.xml")) {
                ExData exData = new ExData();
                new XmlSerializer(typeof(ExData)).Serialize(textWriter, exData);
                textWriter.Close();
            }
        }
    }

public class Data {
    [DefaultValue(10)] public int A { get; set; }
    public Data() { A = 10; }
}

public class ExData : Data {
    [DefaultValue(20)] public new int A { get; set; }
    public ExData() { A = 20; }
}

}

While the first serialization is as i expect (non-serialization of default value): 虽然第一次序列化是我所期望的(默认值的非序列化):

<?xml version="1.0" encoding="utf-8" ?> 
  <Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" /> 

the second results in: 第二个结果是:

<?xml version="1.0" encoding="utf-8"?>
<ExData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <A>20</A>
</ExData>

Obviously XmlSerializer takes the default value of the base class instead of taking the new one. 显然,XmlSerializer采用基类的默认值,而不采用新的默认值。 Overiding a virtual property with "override" gives the same result. 用“替代”覆盖虚拟属性会得到相同的结果。 Changing the initialization of ExData's property A to 10 results in not serializing this property as if the default value of the base class property is applied. 将ExData的属性A的初始化更改为10会导致未序列化此属性,就像应用基类属性的默认值一样。 Can anybody explain this behaviour to me? 有人可以向我解释这种行为吗? Does anybody know a work around to this? 有人知道解决此问题的方法吗?

My aim is to non-serialize default values but changing default value for a derived class. 我的目标是非序列化默认值,但更改派生类的默认值。

The XmlSerializer seems to get only the first DefaultValueAttribute and I unfortunately think there's no direct workaround to what you need. XmlSerializer似乎只获得第一个DefaultValueAttribute ,但不幸的是,我认为没有直接的替代方法可以解决您所需要的问题。 You can however implement IXmlSerializable and do that kind stuff yourself. 但是,您可以实现IXmlSerializable并自己做这种事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM