gpt4 book ai didi

c# - 派生类的 XMLIgnore 属性

转载 作者:行者123 更新时间:2023-12-05 04:16:53 25 4
gpt4 key购买 nike

我在标有 XmlIgnore 属性的基类中有一个属性。当我派生此类并且不覆盖(而不是 Xml-attributes in interfaces and abstract classes )此属性时,是否保留此属性以便派生类具有也具有 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());

}
}

关于c# - 派生类的 XMLIgnore 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25719916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com