简体   繁体   English

是否可以在派生类中添加XmlIgnore属性?

[英]Is it possible to add XmlIgnore attribute in derived classes?

I have class Animal and classes Dog and Cat inheriting from it. 我有动物类,从它那里继承了狗和猫类。 Class Animal has property X. I would like to generate XML for "Dog" without "X" property and for "Cat" with "X" property. 动物类具有属性X。我想为不具有“ X”属性的“狗”和具有“ X”属性的“猫”生成XML。 XmlIgnore doesn't work here in the way I expected. XmlIgnore无法按我期望的方式在这里工作。

I tried to use virtual property and then override it in derived class but it didn't work. 我尝试使用虚拟属性,然后在派生类中覆盖它,但是它不起作用。

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; }
}
public class Cat : Animal
{
    public override int X { get; set; }
}

Even though you don't need this anymore, I still found the solution to this problem. 即使您不再需要它,我仍然找到了解决该问题的方法。

You can create XmlAttributeOverrides and set the XmlAttributes.XmlIgnore Property for certain fields of classes. 您可以创建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;
}

Of course you can also do the opposite by setting attrs.XmlIgnore to false . 当然,您也可以通过将attrs.XmlIgnore设置为false来执行相反的attrs.XmlIgnore

Check this out for more information. 查看以获取更多信息。

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

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