加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#ISerializable问题

发布时间:2020-12-16 10:16:31 所属栏目:百科 来源:网络整理
导读:我打算用序列化做克隆.我必须让我的课程ISerializable.但是它的超级类和所有引用的变量类呢?我需要将它们全部变为ISerializable吗? 如果我使用ISerializable.我必须实现GetObjectData(),我应该放在该方法中?把它留空是好的吗? 解决方法 Unless you mark
我打算用序列化做克隆.我必须让我的课程ISerializable.但是它的超级类和所有引用的变量类呢?我需要将它们全部变为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.如果将其留空,则您的对象将没有所需的值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读