SerializationException:值已被序列化
本文关键字:序列化 SerializationException | 更新日期: 2023-09-27 18:22:14
我在类上实现了ISerializable接口,因此我将数据序列化如下:
[Serializable]
public class MyClass: ISerializable
{
public MyClass() {//default constructor}
public int foo = 5;
public GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("foo",foo,typeof(int));
}
}
这编译了whiteout错误。但是后来我决定要向MyClass
类添加一个float
成员,所以现在我对MyClass
的定义是:
[Serializable]
public class MyClass: ISerializable
{
public MyClass() {//default constructor}
public int foo = 5;
public float ffoo = 3.14; //the added member
public GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("foo",foo,typeof(int));
info.AddValue("ffoo",ffoo,typeof(float));
}
}
但是现在抛出SerializationException
,表示value(foo
)变量已经序列化。那么我该如何避免这种行为呢?因为我确信以后我会向我的类添加更多需要序列化的成员。
这是因为构造函数是为反序列化而调用的,并且info已经包含成员foo。
在该构造函数中,您应该从信息中读取字段值。ISerializable有另一个用于序列化的方法(GetObjectData),您应该将字段添加到该方法体中的信息中,而不是添加到构造函数中。