C#ISerializable的问题 [英] C# ISerializable question

查看:426
本文介绍了C#ISerializable的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算使用序列做克隆。我必须让我的类ISerializable的。但如何对其超类和所有引用变量类?我需要让他们都ISerializable的?



如果我用了ISerializable。我必须实现GetObjectData使用(),我应该把这个方法里面呢?让它空是确定的?


解决方案

除非您将与
[类Serializable]属性,这个
接口必须由所有
类与序列化实例来实现。使用
如果你
想让你的类来控制自己的
序列化和反序列化ISerializable接口。




该GetObjectData使用()可以让您控制序列化过程。




GetDataObject,为您传递一个
的SerializationInfo对象和
的StreamingContext对象。然后
GetDataObject方法将
填充的SerializationInfo对象
相所需的目标对象的
序列的数据




例如:

 公务员(的SerializationInfo信息,的StreamingContext ctxt)
{
//从信息获取的值,并将其分配给相应的属性
EMPID =(INT)info.GetValue(雇员的typeof(INT));
EmpName =(字符串)info.GetValue(EmployeeName,typeof运算(字符串));
}

公共无效GetObjectData使用(的SerializationInfo信息,的StreamingContext ctxt)
{
//你可以为你的名字 - 值对使用任何自定义名称。但要确保你
//同名的读出值。对于前: - 如果你写EMPID为雇员
//那么你应该读与雇员
info.AddValue(雇员,EMPID)相同;
info.AddValue(EmployeeName,EmpName);
}



上面展示的例子中,你如何反序列化和序列化。正如你所看到GetObjectData使用需要反序列化。如果你把它空的,你的对象不会有欲望值。


I am planning to use serialization to do clone. I have to make my class ISerializable. But how about its super classes and all referenced variable classes? do I need to make them all ISerializable?

If I use ISerializable. I have to implement the GetObjectData(), what I should put inside that method? leave it empty is ok?

解决方案

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.

The GetObjectData() let you control the serialization process.

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.

Example:

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

The example above show you how to deserialize and serialize. As you can see GetObjectData is required to deserialize. If you leave it empty, your object won't have the desire values.

这篇关于C#ISerializable的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆