在c#中序列化2D对象数组时遇到问题
本文关键字:数组 遇到 问题 对象 2D 序列化 | 更新日期: 2023-09-27 18:03:35
我有一个2D对象数组。层次结构如下所示:
PixelData : ISerializable
-Rectangle
-SerialColor
SerialColor : ISerializable
-R
-G
-B
当我序列化它们的2d数组时,我没有得到错误消息。但是,我在文本编辑器中打开它序列化的文件,注意到大约在第10行之后,它开始破坏数据。数组的大小是50 x 50。我试过用不同的方法序列化对象。同样,在序列化数据时不会出现错误消息。当我试图反序列化数据时,我得到了可怕的异常。我该怎么办?
例外是System.Reflection.TargetInvocationException: exception has been thrown by the target of an invocation
[Serializable()]
public class PixelData : ISerializable
{
#region Constructors
public PixelData()
: this(new Rectangle(0, 0, 0, 0), Color.White)
{
}
public PixelData(Rectangle r, Color c)
{
this.BoundingRect = r;
this.CellColor = c;
}
public PixelData(SerializationInfo info, StreamingContext ctxt)
{
this.BoundingRect = (Rectangle)info.GetValue("BoundingRect", typeof(Rectangle));
SerialColor c = (SerialColor)info.GetValue("CellColor", typeof(SerialColor));
this.CellColor = c.GetColor();
}
#endregion
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("BoundingRect", BoundingRect);
info.AddValue("CellColor", new SerialColor(CellColor));
}
#endregion
#region Properties
public Rectangle BoundingRect
{
get;
set;
}
public Color CellColor
{
get;
set;
}
#endregion
}
和SerialColor类
[Serializable()]
public class SerialColor : ISerializable
{
public SerialColor()
: this(0, 0, 0)
{
}
public SerialColor(int r, int g, int b)
{
R = r;
G = g;
B = b;
}
public SerialColor(Color c)
{
R = c.R;
G = c.G;
B = c.B;
}
public SerialColor(SerializationInfo info, StreamingContext ctxt)
{
R = (int)info.GetValue("R", typeof(int));
G = (int)info.GetValue("G", typeof(int));
B = (int)info.GetValue("B", typeof(int));
}
#endregion
#region Methods
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("R", R);
info.AddValue("G", G);
info.AddValue("B", B);
}
public Color GetColor()
{
Color c = Color.FromArgb(R, G, B);
try
{
//this will throw an exception if the name of the color is not hexadecimal
Int32.Parse(c.Name, System.Globalization.NumberStyles.HexNumber);
//attempt to create a non-hex name for the color
return ColorTranslator.FromHtml("#" + c.Name);
}
catch (Exception e)
{
//returns the name if it is not hexadecimal
return c;
}
}
public override string ToString()
{
Color c = this.GetColor();
return c.Name + "[ " + c.R.ToString() + " , " + c.G.ToString() + " , " + c.B.ToString() + " ]";
}
public override bool Equals(object obj)
{
if (!(obj is SerialColor))
return false;
SerialColor other = (SerialColor)obj;
return ((this.R == other.R) && (this.G == other.G) && (this.B == other.B));
}
public override int GetHashCode()
{
return this.GetColor().GetHashCode();
}
#endregion
#region Properties
public int R
{
get;
set;
}
public int G
{
get;
set;
}
public int B
{
get;
set;
}
#endregion
}
编辑:好的,我还创建了一个SerialRectangle类,因为我浏览了文档,发现Rectangle是一个结构体。这个类与SerialColor类非常相似。
我将在所有异常上打开break并在调试选项中关闭我的代码然后运行serialize代码,看看它是否看到了序列化通常会包含的异常