我打算用序列化做克隆.我必须让我的课程ISerializable.但是它的超级类和所有引用的变量类呢?我需要将它们全部变为ISerializable吗?
如果我使用ISerializable.我必须实现GetObjectData(),我应该放在该方法中?把它留空是好的吗?
除非使用[Serializable]属性标记类,否则此接口必须由具有序列化实例的所有类实现.如果希望类控制自己的序列化和反序列化,请使用ISerializable接口.
GetObjectData()允许您控制序列化过程.
GetDataObject,您向其传递SerializationInfo对象和StreamingContext对象.然后,GetDataObject方法将使用序列化目标对象所需的数据填充SerializationInfo对象.
例:
public Employee(SerializationInfo info, StreamingContext ctxt)
{
//Get the values from info and assign them to the appropriate properties
EmpId = (int)info.GetValue("EmployeeId", typeof(int));
EmpName = (String)info.GetValue("EmployeeName", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
//You can use any custom name for your name-value pair. But make sure you
// read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
// then you should read the same with "EmployeeId"
info.AddValue("EmployeeId", EmpId);
info.AddValue("EmployeeName", EmpName);
}
Run Code Online (Sandbox Code Playgroud)
上面的示例显示了如何反序列化和序列化.如您所见,反序列化需要GetObjectData.如果将其留空,则您的对象将没有所需的值.