为什么DataTable可序列化?

时间:2013-05-02 21:03:03

标签: c# serialization

所以这是一个简单的测试用例:

[Serializable]
class Base
{

}

[Serializable]
class Derived : Base
{

}

BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, new Derived());

这里没什么特别的。如果您删除任何一个'Serializable'标签,那么BinaryFormatter会对您大喊大叫,因为这些项目不可序列化。理论上,序列化DataTable不应该起作用,因为DataTable的基类 - 'MarshalByValueComponent - isn't marked as serializeable either ('typeof(MarshalByValueComponent).IsSerializable返回'false')。那么为什么BinaryFormatter忽略了这个而不是其他不可序列化的类型呢? (或者为什么MarshalByValueComponent不能标记为可序列化?)

1 个答案:

答案 0 :(得分:4)

DataSet类的定义如下:

[SerializableAttribute]
public class DataSet : MarshalByValueComponent, IListSource, 
    IXmlSerializable, ISupportInitializeNotification, ISupportInitialize, ISerializable

请参阅:http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx

正如您所看到的,ISerializable接口有一个实现。此接口允许对象控制自己的序列化和反序列化。

相关问题