What's the difference between using the Serializable attribute & implementing ISerializable?

放肆的年华 提交于 2019-12-17 08:54:41

问题


What's the difference between using the Serializable attribute and implementing the ISerializable interface?


回答1:


When you use the SerializableAttribute attribute you are putting an attribute on a field at compile-time in such a way that when at run-time, the serializing facilities will know what to serialize based on the attributes by performing reflection on the class/module/assembly type.

[Serializable]
public class MyFoo { … }

The above indicates that the serializing facility should serialize the entire class MyFoo, whereas:

public class MyFoo
{
    private int bar;

    [Serializable]
    public int WhatBar
    {
       get { return this.bar; }
    }
}

Using the attribute you can selectively choose which fields needs to be serialized.

When you implement the ISerializable interface, the serialization effectively gets overridden with a custom version, by overriding GetObjectData and SetObjectData (and by providing a constructor of the form MyFoo(SerializationInfo info, StreamingContext context)), there would be a finer degree of control over the serializing of the data.

See also this example of a custom serialization here on StackOverflow. It shows how to keep the serialization backwards-compatible with different versionings of the serialized data.

Hope this helps.




回答2:


The SerializableAttribute instructs the framework to do the default serialization process. If you need more control, you can implement the ISerializable interface. Then you would put the your own code to serialize the object in the GetObjectData method and update the SerializationInfo object that is passed in to it.




回答3:


The ISerializable interface lets you implement custom serialization other than default. When you implement the ISerializable interface, you have to override GetObjectData method as follows

public void GetObjectData (SerializationInfo serInfo, 
                                    StreamingContext streamContext)
{
   // Implement custom Serialization
}



回答4:


ISerialize force you to implement serialization logic manially, while marking by Serializable attribute (did you mean it?) will tell Binary serializer that this class can be serialized. It will do it automatically.




回答5:


Inheriting from ISerializable allows you to custom implement the (de)serialization. When using only the Serializable attribute, the (de)serialization can be controlled only by attributes and is less flexible.



来源:https://stackoverflow.com/questions/2365152/whats-the-difference-between-using-the-serializable-attribute-implementing-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!