Ignore inherited class when serializing object

后端 未结 4 1434
不思量自难忘°
不思量自难忘° 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: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();
                        }
                    }
                }
            }
    

提交回复
热议问题