How do we ignore a particular base class member when serializing an object of derived class?
The base class in my case is UndirectedGraph
(from QuickGraph library). Among other things there are two members in this class that I don't want to serialize:
public class UndirectedGraph<TVertex, TEdge>
{
public IEnumerable<TEdge> Edges { get; }
public IEnumerable<TVertex> Vertices { get; }
}
So I derived from this class and make my own. I then redefined these two members with new
and applied IgnoreDataMember
on them. Like this:
public class OurGraph : UndirectedGraph
{
[IgnoreDataMember]
public new IEnumerable<XMLDoc> Vertices => base.Vertices;
[IgnoreDataMember]
public new IEnumerable<OurEdge> Edges => base.Edges;
}
Now I use DataContractSerializer
to write an object of OurGraph
to a file:
public static string SerializeDC(this object obj)
{
XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces();
Namespaces.Add(string.Empty, string.Empty);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StringWriter writer = new StringWriter(sb))
{
using (XmlWriter xmlWriter = XmlWriter.Create(writer, myXmlWriterSettings))
{
DSSerializer.WriteObject(xmlWriter, obj);
xmlWriter.Close();
}
writer.Close();
}
return sb.ToString();
}
Unfortunately, those two members still find their way into the output. What am I doing wrong?
While doing further experimentation, it looks like IgnoreDataMember
will not work unless you apply DataContract
attribute on the containing class. Now applying DataContract
attribute on a class requires its base class to also have DataContract
(or Serializable
) attribute applied on it, which in my case is a third-party class and I can't change that code.
Am I out of luck?
Hope this will solve your issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.