我有Animal类,并且从它那里继承了Dog and Cat类。动物类具有属性X。 我想为不具有“ X”属性的“狗”和具有“ X”属性的“猫”生成XML。 XmlIgnore无法按我期望的方式在这里工作。
我尝试使用虚拟属性,然后在派生类中覆盖它,但是它不起作用。
pdate status total total_amount percentage
2019-04-01, successful, 10, 100, 50%
2019-04-01, failed, 5, 50, 25%
2019-04-01, refunded, 5, 50, 25%
2019-04-02, successful, 12, 120, 58.3%
2019-04-02, failed, 5, 50, 16.6%
2019-04-02, refunded, 3, 30, 25%
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Cat cat = new Cat();
SerializeToFile(dog, "testDog.xml");
SerializeToFile(cat, "testCat.xml");
}
private static void SerializeToFile(Animal animal, string outputFileName)
{
XmlSerializer serializer = new XmlSerializer(animal.GetType());
TextWriter writer = new StreamWriter(outputFileName);
serializer.Serialize(writer, animal);
writer.Close();
}
}
public abstract class Animal
{
public virtual int X { get; set; }
}
public class Dog : Animal
{
[XmlIgnore]
public override int X { get; set; }
}
答案 0 :(得分:0)
即使您不再需要它,我仍然找到了解决此问题的方法。
您可以创建XmlAttributeOverrides
并为类的某些字段设置XmlAttributes.XmlIgnore
属性。
private static void SerializeToFile(Animal animal, string outputFileName)
{
// call Method to get Serializer
XmlSerializer serializer = CreateOverrider(animal.GetType());
TextWriter writer = new StreamWriter(outputFileName);
serializer.Serialize(writer, animal);
writer.Close();
}
// Return an XmlSerializer used for overriding.
public XmlSerializer CreateOverrider(Type type)
{
// Create the XmlAttributeOverrides and XmlAttributes objects.
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
/* Setting XmlIgnore to true overrides the XmlIgnoreAttribute
applied to the X field. Thus it won't be serialized.*/
attrs.XmlIgnore = true;
xOver.Add(typeof(Dog), "X", attrs);
XmlSerializer xSer = new XmlSerializer(type, xOver);
return xSer;
}
当然,您也可以通过将attrs.XmlIgnore
设置为false
来相反。
签出this以获得更多信息。