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
}
}
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);
}
请注意,如果您尝试反序列化未使用创建的XMLXmlSerializer
或您的Shape
类未正确实现,则序列化/反序列化周期可能会失败或无法正常工作ISerializable
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句