欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#自定义序列化ISerializable的实现方法

程序员文章站 2022-07-01 17:10:50
本文实例讲述了c#自定义序列化iserializable的实现方法。分享给大家供大家参考。具体实现方法如下: [serializable] public cla...

本文实例讲述了c#自定义序列化iserializable的实现方法。分享给大家供大家参考。具体实现方法如下:

[serializable]
public class baseobject
{
  [optionalfield]
  private string _str = "i am baseobject";
}
[serializable]
public class testobject : baseobject, iserializable
{
  int a;
  string strname = "";
  color c = color.red;
  datatable _dtcolors = null;
  [optionalfield]
  arraylist list = new arraylist();
  [optionalfield]
  list<int> list1 = new list<int>();
  [optionalfield]
  dictionary<int, string> dic = new dictionary<int, string>();
  //当实现iserializable接口时,如果该构造函数不存在,则会引发一个serializationexception异常
  //该特性表示,该方法只允许序列化器调
  [securitypermissionattribute(securityaction.demand, serializationformatter = true)]
  protected testobject(serializationinfo info, streamingcontext context)
  {
   #region 如果基类也实现了iserializable接口,则序列化器会自动调用基类的该构造函数,就不需要本段代码
   type basetype = this.gettype().basetype;
   memberinfo[] mi = formatterservices.getserializablemembers(basetype, context);
   for (int i = 0; i < mi.length; i++)
   {
    //由于addvalue不能添加重名值,为了避免子类变量名与基类变量名相同,将基类序列化的变量名加上基类类名
    fieldinfo fi = (fieldinfo)mi[0];
    object objvalue = info.getvalue(basetype.fullname + "+" + fi.name, fi.fieldtype);
    fi.setvalue(this, objvalue);
   }
   #endregion
   a = info.getint32("a");
   strname = info.getstring("strname");
   c = (color)info.getvalue("c", typeof(color));
   _dtcolors = (datatable)info.getvalue("_dtcolors", typeof(datatable));
   list = (arraylist)info.getvalue("list", typeof(arraylist));
   list1 = (list<int>)info.getvalue("list1", typeof(list<int>));
   dic = (dictionary<int, string>)info.getvalue("dic", typeof(dictionary<int, string>));
  }
  public testobject()
  {
   a = 100;
   strname = "daps";
   initcolortable();
   list1.add(10);
   list1.add(20);  
  }
  #region iserializable 成员
  [securitypermissionattribute(securityaction.demand, serializationformatter =true)]
  void iserializable.getobjectdata(serializationinfo info, streamingcontext context)
  {
   info.addvalue("a", a);
   info.addvalue("strname", strname);
   info.addvalue("c", c);
   info.addvalue("_dtcolors", _dtcolors);
   info.addvalue("list", list);
   info.addvalue("list1", list1);
   info.addvalue("dic", dic);
   type basetype = this.gettype().basetype;
   memberinfo[] mi = formatterservices.getserializablemembers(basetype, context);
   for (int i = 0; i < mi.length; i++)
   {
    //由于addvalue不能添加重名值,为了避免子类变量名与基类变量名相同,将基类序列化的变量名加上基类类名
    info.addvalue(basetype.fullname + "+" + mi[i].name, ((fieldinfo)mi[i]).getvalue(this));
   }
  }
  #endregion
}

希望本文所述对大家的c#程序设计有所帮助。