Как вы десериализуете производный класс при передаче параметров в базовый класс

У меня есть производный класс, который наследуется от класса баса, который рисует круг

    public BraceHole(Brace brace, Vertex centerPoint, double diameter, VDrawI5.vdEntities entities) : base(centerPoint, diameter / 2, entities)
    {
        this.brace = brace;
        this.centerPoint = centerPoint;
        this.radius = diameter/2;
    }

Я пытаюсь сериализовать этот класс, используя двоичную сериализацию.

Я сериализую это так:

   public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("brace", brace, typeof(Brace));
        info.AddValue("radius", radius, typeof(double));
        info.AddValue("centerPoint", centerPoint, typeof(Vertex));
    }

С сериализацией все в порядке, но когда я ее десериализую, как показано ниже: Я возвращаю поля данных (скобка, радиус и центральная точка) в порядке; но я не получаю круг обратно! Я подозреваю, что это потому, что я не десериализую базовый класс. Как бы я ни пытался, я не знаю, как это сделать!

    protected BraceHole(SerializationInfo info, StreamingContext context)
    {
       try {
            brace = (Brace)info.GetValue("brace", typeof(Brace));
            radius = (double)info.GetValue("radius", typeof(double));
            centerPoint = (Vertex)info.GetValue("centerPoint", typeof(Vertex));
        }
       catch{} 
    }

Мой вопрос в том, как я могу десериализовать это. Я ищу что-то подобное, это возможно?

  protected BraceHole(SerializationInfo info, StreamingContext context) : base(centerPoint, radius, entities)
    {
       VdProControl.VdProControl vectorDraw = (VdProControl.VdProControl)context.Context;
       VDrawI5.vdEntities entities = vectorDraw.ActiveDocument.Entities;

       try {
            brace = (Brace)info.GetValue("brace", typeof(Brace));
            radius = (double)info.GetValue("radius", typeof(double));
            centerPoint = (Vertex)info.GetValue("centerPoint", typeof(Vertex));
        }
       catch{} 
    }

person Charlie Liu    schedule 18.09.2014    source источник


Ответы (1)


Что вам нужно сделать, так это сериализовать базовый класс (что вы в настоящее время не делаете) и иметь защищенный конструктор в базовом классе, который принимает SerializationInfo и StreamingContext для его десериализации.

//This is now a override of the virtual function defined in Circle
public override void GetObjectData(SerializationInfo info, StreamingContext context)     
{
    base.GetObjectData(info, context); //Get the base class data
    info.AddValue("brace", brace, typeof(Brace));
    info.AddValue("radius", radius, typeof(double));
    info.AddValue("centerPoint", centerPoint, typeof(Vertex));
}

protected BraceHole(SerializationInfo info, StreamingContext context) 
    : base(info, context) //Deserialize the base class data.
{
   // The commented code would likely now go in the base class's protected constructor.
   //VdProControl.VdProControl vectorDraw = (VdProControl.VdProControl)context.Context;
   //VDrawI5.vdEntities entities = vectorDraw.ActiveDocument.Entities;

   try {
        brace = (Brace)info.GetValue("brace", typeof(Brace));
        radius = (double)info.GetValue("radius", typeof(double));
        centerPoint = (Vertex)info.GetValue("centerPoint", typeof(Vertex));
    }
   catch
   {
       //This empty try-catch is a bad idea, if something goes wrong you should 
       //at minimum log it some how. It would be better to get rid of it and let 
       //the caller catch the exception.
   } 
}

Вам нужно будет изменить Circle, чтобы иметь новый конструктор и виртуальный метод GetObjectData

person Scott Chamberlain    schedule 18.09.2014
comment
Спасибо! именно то, что я искал - person Charlie Liu; 18.09.2014