0

我有一个派生类,它继承自一个绘制圆圈的低音类

    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{} 
    }
4

1 回答 1

1

您需要做的是序列化基类(您当前没有这样做)并在基类中有一个受保护的构造函数来接收SerializationInfoStreamingContext反序列化它。

//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

于 2014-09-18T15:09:43.097 回答