序列化 - 实现ISerializable

我们可以实现ISerializable接口来自定义串行化行为。这个接口只有一个方法GetObjectData。这个方法用于将对类对象进行序列化所需的数据填进SerializationInfo对象。你使用的格式化器(比如BinaryFormatter)将构造SerializationInfo对象,然后在序列化时调用GetObjectData。因此,你需要实现GetObjectData,让它添加你从类中选择的值,并且映射到你选择的字符串名。注意,如果类的父类也实现ISerializable,那么应该调用GetObjectData的父类实现。
给出例子:
None.gif using  System;
None.gif
using  System.IO;
None.gif
using  System.Runtime.Serialization;
None.gif
using  System.Runtime.Serialization.Formatters.Binary;
None.gif[Serializable]
None.gif
public   class  Insect : ISerializable
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
private string name;
InBlock.gif    
private int id;
InBlock.gif    
public Insect(string name, int id)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
this.name = name;
InBlock.gif        
this.id = id;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
public override string ToString()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return String.Format("{0}:{1}", name, id);
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public Insect()dot.gif{}
InBlock.gif    
InBlock.gif    
public virtual void GetObjectData(SerializationInfo s, StreamingContext c)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        s.AddValue(
"CommonName", name);
InBlock.gif        s.AddValue(
"ID#", id);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
private Insect(SerializationInfo s, StreamingContext c)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        name 
= s.GetString("CommonName");
InBlock.gif        id 
= s.GetInt32("ID#");
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
class  ImpISerialApp
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Insect i 
= new Insect("Meadow Brown"12);
InBlock.gif        Stream s 
= File.Create("Insect.bin");
InBlock.gif        BinaryFormatter b 
= new BinaryFormatter();
InBlock.gif        b.Serialize(s, i);
InBlock.gif        s.Seek(
0, SeekOrigin.Begin);
InBlock.gif        Insect j 
= (Insect)b.Deserialize(s);
InBlock.gif        s.Close();
InBlock.gif        Console.WriteLine(j);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

Insect.bin包含以下信息:
DISerializable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Insect
CommonName ID# Meadow Brown
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值