我有一个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类非常相似。这并没有解决问题。
答案 0 :(得分:1)
我会打开所有异常中断并在调试选项中关闭我的代码然后运行序列化代码并查看是否看到序列化通常吞下的异常