派生类的XMLIgnore特性
本文关键字:特性 XMLIgnore 派生 | 更新日期: 2023-09-27 18:20:57
我在用XmlIgnore
-属性标记的基类中有一个属性。当我派生这个类并且不重写(与接口和抽象类中的Xml属性相反)这个属性时,是保留这个属性以使派生类具有同时具有XmlIgnore
-属性的属性,还是必须重写该属性才能重置该属性?
如果派生类没有用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());
}
}