0

鉴于以下类结构,Bar 会按预期进行序列化/反序列化吗?

public class Foo { int x; string y; }

[Serializable]
public class Bar {
   Foo[] AllFoos;
   Foo SelectedFoo;

   public Bar(Foo[] allFoos, int selectedFooIndex) { 
     this.AllFoos = allFoos; 
     this.SelectedFoo = allFoos[selectedFooIndex]; 
   } 
}

我对几件事感到好奇:

1) BinaryFormatter 是否要求 Bar 类用 [Serializable] 属性装饰或实现 ISerializable 接口?

2) Foo 类是否也需要用 [Serializable] 属性装饰?

3) 如果 Bar 简单地用 [Serializable] 属性装饰,那么字段 Bar.SelectedFoo 是否会正确地保持其对数组的引用?还是我会得到一份 Foo 的副本?

4

1 回答 1

2

1) BinaryFormatter 是否要求 Bar 类用 [Serializable] 属性装饰或实现 ISerializable 接口?

是的,如果要使用 BinaryFormatter 序列化 Bar 实例,它确实如此。

2) Foo 类是否也需要用 [Serializable] 属性装饰?

Yes, unless you create a custom serialization mechanism that does not involve serializing an instance of a Foo object. For example, you could serialize the x and y components separately, and create a new Foo instance from them in your deserialization code. Otherwise, it must have the attribute or interface.

3) If Bar is simply decorated with the [Serializable] attribute, will the field Bar.SelectedFoo maintain its reference into the array correctly? or will I wind up with a copy of that Foo?

If I remember correctly, arrays are not serializable like this. You must provide your own mechanism (through the ISerializable inteface) for writing and reading arrays.

However, in general, if a graph of serializable objects with mutual references to each other is serialized with the BinaryFormatter, then it will recreate the references correctly without duplicating objects. This should include objects that you specify in your custom serialization code as well, so long as you decorate your Foo with Serializable and pass the same object instance to the formatter from both the array and the field.

于 2011-04-07T21:04:22.213 回答