gpt4 book ai didi

C# ISerializable 问题

转载 作者:行者123 更新时间:2023-11-30 13:29:08 24 4
gpt4 key购买 nike

我打算使用序列化来做克隆。我必须让我的类 ISerializable。但是它的父类(super class)和所有引用的变量类呢?我需要让它们全部 ISerializable 吗?

如果我使用 ISerializable。我必须实现 GetObjectData(),我应该在该方法中放入什么?留空可以吗?

最佳答案

Unless you mark the class with the [Serializable] attribute, this interface must be implemented by all classes with serialized instances. Use the ISerializable interface if you want your class to control its own serialization and de-serialization.

GetObjectData() 让您控制序列化过程。

GetDataObject, to which you pass a SerializationInfo object and a StreamingContext object. The GetDataObject method will then populate the SerializationInfo object with the data necessary for the serialization of the target object.

例子:

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);
}

上面的例子展示了如何反序列化和序列化。如您所见,反序列化需要 GetObjectData。如果将其留空,您的对象将没有所需的值。

关于C# ISerializable 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2479158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com