代码之家  ›  专栏  ›  技术社区  ›  TerribleDog

如何在反序列化中修复此错误?

  •  0
  • TerribleDog  · 技术社区  · 7 年前

    screator.exe中发生“system.invalidcastexception”类型的未处理异常。 其他信息:无法将“system.string”类型的对象强制转换为“screator.shape”类型。

    代码如下:

        public void Deseriaize(StreamReader file)
        {
            XmlSerializer ser = new XmlSerializer(typeof(string));
            Shape s = (Shape)ser.Deserialize(file);
            file.Close();
            MessageBox.Show(s.title);
        }
    
        private void btn_OpenProject_Click(object sender, EventArgs e)
        {
            StreamReader file = new StreamReader(@"C:\Users\pb8n0053\Documents\SerializationOverview.seal");
            Deseriaize(file);
        }
    

    形状类

     [Serializable]
    public class Shape
    {
        //Properties
        public Draw draw;
        public String title;
        public float width { get; set; }
        public float height { get; set; }
        public float x { get; set; }
        public float y { get; set; }
        public static PointF center = new PointF(250f, 250f);
        public int strokeThickness { get; set; }
        public Color color { get; set; }
        public float userDefinedWidth { get; set; }
        public float userDefinedHeight { get; set; }
        public int userDefinedStroke { get; set; }
        public SizeF size;
        public PointF location;
        public float radius;
        public ShapeType type;
        public Status status;
        public enum ShapeType
        {
            rectangle, square, circle, ellipse, triangle, image
        }
        public enum Status
        {
            editing, start
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   laptou    7 年前

    你的 XmlSerializer 正在用创建 typeof(string) 作为构造函数的参数。这意味着序列化程序将XML与 System.String . 如果希望它将XML与 Shape 键入,然后使用它初始化:

    public void Deseriaize(StreamReader file)
    {
        XmlSerializer ser = new XmlSerializer(typeof(Shape));
        Shape s = (Shape)ser.Deserialize(file);
        file.Close();
        MessageBox.Show(s.title);
    }
    

    请注意,如果试图反序列化未使用创建的XML,则序列化/反序列化循环可能会失败或工作不正常。 XML串行化器 或者如果你 形状 类未正确实现 ISerializable .