【发布时间】:2014-09-08 08:15:08
【问题描述】:
我在标有XmlIgnore-attribute 的基类中有一个属性。当我派生此类并且不覆盖(与Xml-attributes in interfaces and abstract classes相反)此属性时,是否保留此属性以便派生类也具有XmlIgnore-attribute的属性,或者我是否必须覆盖该属性才能重置属性?
【问题讨论】:
标签: c# inheritance xml-serialization
我在标有XmlIgnore-attribute 的基类中有一个属性。当我派生此类并且不覆盖(与Xml-attributes in interfaces and abstract classes相反)此属性时,是否保留此属性以便派生类也具有XmlIgnore-attribute的属性,或者我是否必须覆盖该属性才能重置属性?
【问题讨论】:
标签: c# inheritance xml-serialization
如果您的派生类没有使用 XmlIgnore 属性集覆盖该属性,则该属性将在序列化时被适当地忽略。
如果您的派生类确实覆盖了该属性,并且忘记设置 XmlIgnore 属性,则该属性将被适当地序列化。
显示行为的示例代码:
using System;
using System.Linq;
using System.Reflection;
using System.Xml.Serialization;
[Serializable]
public abstract class myBaseClass
{
[XmlIgnore]
public virtual bool aBoolean { get; set; }
public int anInt { get; set; }
}
[Serializable]
public class myDerivedClass : myBaseClass
{
public string derivedString { get; set; }
}
[Serializable]
public class overrideXmlIgnore : myBaseClass
{
// no XmlIgnore
public override bool aBoolean
{
get
{
return base.aBoolean;
}
set
{
base.aBoolean = value;
}
}
}
class Program
{
static void Main(string[] args)
{
// build array of types we can serialize/deserialize
// uses Linq and Reflection namespaces
Type[] derivedTypes = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies()
from lType in lAssembly.GetTypes()
where typeof(myBaseClass).IsAssignableFrom(lType)
select lType).ToArray();
// build a test object to serialize with XMLIgnore still used
myDerivedClass m = new myDerivedClass();
m.aBoolean = true; // this property is ignored by default
m.derivedString = "test";
// set a file path to serialize to
string testFilePath = "C:\\temp\\test.xml";
// serialzie the object
XmlSerializer x = new XmlSerializer(typeof(myBaseClass), derivedTypes);
System.IO.StreamWriter sw = new System.IO.StreamWriter(testFilePath);
x.Serialize(sw, m);
sw.Close();
// deserialize the object
System.IO.StreamReader sr = new System.IO.StreamReader(testFilePath);
myBaseClass deserializedObject = (myBaseClass)x.Deserialize(sr);
sr.Close();
// check the object's properties
// aBoolean is false, even though the serialized object m set it to true, because of XmlIgnore
Console.WriteLine("aBoolean = " + deserializedObject.aBoolean.ToString());
// repeat process for the derived class that overrides and does not set XmlIgnore
overrideXmlIgnore o = new overrideXmlIgnore();
o.aBoolean = true;
sw = new System.IO.StreamWriter(testFilePath);
x.Serialize(sw, o);
sw.Close();
sr = new System.IO.StreamReader(testFilePath);
deserializedObject = (myBaseClass)x.Deserialize(sr);
// check the object's properties
// aBoolean is true, as we no longer XmlIgnore
Console.WriteLine("aBoolean = " + deserializedObject.aBoolean.ToString());
}
}
【讨论】:
XmlIgnore 在隐藏或覆盖的属性”只是重新描述了答案中解释的行为。至于它是否是一个错误,我很难评论。 XmlIgnore 和 XmlSerializer 的文档对于派生类的预期行为并不清楚。 (序列化程序的第一个构造函数参数中的“主”类型是基类型还是派生类型也可能很重要。在答案中,基类型是使用的类型,因为这是序列化基时的常见模式类型。)