简体   繁体   中英

serialize base class property in one derived class without serializing it in second serialize class

I am looking an issue, but i am still confuse how to tackle this. I have base class and there are some properties. There are two derived classes from base class.

I want to serialize base class property in one derived class but i don't want to serialize same property in second serialize class.

This is not actual code just for example purpose only.

public class BaseRouter
{

    private Double r;  
    private Double bch;  

    [XmlElement("BaseRouter.r")]
    public double R { get { return r; } set { r = value; } }


    }

First derived class

      public class CiscoRouter : BaseRouter
{
    private String mRID; 

    [XmlAttribute("ID", Namespace = "rdf")]
    public String MRID { get { return this.mRID; } set { mRID = value; } }
    public Router()
    {

    }

Second derived class

 public class DellRouter : BaseRouter
{
    private String mRID; 

    [XmlAttribute("ID", Namespace = "rdf")]
    public String MRID { get { return this.mRID; } set { mRID = value; } }
    public Router()
    {

    }

}

How can I avoid BaseRouter.r in DellRouter class and include in CiscoRouter serialization?

Define an abstract method in the base class, this will be used to do serialization/initialization. In the class where you want to serialize BaseRouter.r serialize it in this methods implementation. In the other class, do whatever would be a logical substitute.

I believe you can implement a public ShouldSerializeR() function and override it in your DellRouter class to return false.

class BaseRouter
{
    ...
    public double R { get { return r; } set { r = value; } }
    public virtual bool ShouldSerializeR() { return true; }
    ...
}

class DellRouter
{
    ...
    public override bool ShouldSerializeR() { return false; }
    ...
}

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.

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