Ignore inherited class when serializing object

后端 未结 4 1433
不思量自难忘°
不思量自难忘° 2021-01-24 21:29

When I inherit from a class and serialize the new class I get all all properties. How can I prevent that? I have no control over the class that I inherit from. So I can\'t add

相关标签:
4条回答
  • 2021-01-24 21:56

    One solution is to use the [Nonserialized] attribute on PropertyA. Note that with this attribute, PropertyA will never be serialized, including when you serialize an instance of class A. Is that acceptable?

    0 讨论(0)
  • 2021-01-24 21:57

    This was the solution I came up with.

            public void WriteXml(XmlWriter writer)
            {
                foreach (PropertyInfo propertyInfo in this.GetType().GetProperties())
                {
                    string name = propertyInfo.Name;
    
                    if (propertyInfo.DeclaringType != typeof(A))
                    {
                        object obj = propertyInfo.GetValue(this, null);
    
                        if (obj != null)
                        {
                            writer.WriteStartElement(name);
                            string value = obj.ToString();
                            writer.WriteValue(value);
                            writer.WriteEndElement();
                        }
                    }
                }
            }
    
    0 讨论(0)
  • 2021-01-24 22:11

    Late to the party, but: I just stumbled over your question because I have similar problem. I inherit from a class, but the logic of my derived class renders some properties of the base class redundant or obsolete for serialization, and so I don't want to serialize them.

    I found a solution which isn't as automatic as yours but more flexible: Override the base class properties and mark them with [XmlIgnore]. The implementation in the override can just consist of a call to the base implementation; the only purpose of the overriding is to attach the XmlIgnore attribute to it.

    It's less automatic because if properties in the base class change you have to reflect the changes in the derived class. That's on the other hand more flexible because you can select which properties to ignore.

    Admittedly this solution doesn't scale well and is best suited for smaller projects with close ties between the involved classes and people.

    0 讨论(0)
  • 2021-01-24 22:18

    If B inherits from A, it inherits PropertyA, and there's nothing you can do about it. If you don't want to serialize PropertyA when serializing an instance of B, perhaps you shouldn't be inheriting A in the first place...

    Anyway, I don't think XML serialization can help you with what you're trying to do, unless you implement IXmlSerializable yourself...

    0 讨论(0)
提交回复
热议问题