[已解决问题] 包含泛型集合的类二进制序列化方法
提问时间: 2008-06-23 11:14
悬赏分:200 浏览:303 次

 

提问者:heng_xi - 初学一级

问题补充:现在有一个回答了,没细看,这几天太忙了,没时间验证,过2天验证吧。我的目的是做一个可以对各种类进行各种序列化的内裤。答案1或许可以(没验证)但需要对集合类型的数据类型的属性加上XmlArray和XmlArrayItem两个Attribute的设置,这设置不知道能不能在类库中实现,为客户端降低编码的复杂度。

所有回答(2)
[code] using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { Test t = new Test(); t.ID = 100; t.GenericList = new List<Student>(); Student s = new Student(); s.Id = 10; t.GenericList.Add(s); IFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream,t); byte[] bytes = stream.ToArray(); Console.WriteLine(bytes.Length); Console.Read(); } } [XmlRoot("test"),Serializable] public class Test { private int _id; [XmlAttribute("tid")] public int ID { get { return _id; } set { _id = value; } } private List<Student> genericList; [XmlArray("students"),XmlArrayItem("s")] public List<Student> GenericList { get { return genericList; } set { genericList = value; } } } [Serializable ,XmlRoot("student")] public class Student { private int _id; [XmlAttribute("id")] public int Id { get { return _id; } set { _id = value; } } } } [/code] 例子中直接用了MemoryStream你可以用FileStream将类反序列化到文件。 关键的地方就是XmlArray和XmlArrayItem两个Attribute的设置;另外Test类和Student类必须用Serializable特性标志为可序列化的。
3个月前   回答者:玉开 - 大侠五级
MyClass myObject = new MyClass(); myObject.Name = "MyClass"; myObject.Items = new List<string>() { "Item1", "Item2", "Item3", }; IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(@"c:\MyFile.dat", FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, myObject); stream.Close(); [Serializable] public class MyClass { public String Name { get; set; } private List<String> _items = new List<string>(); public List<String> Items { get { return this._items; } set { this._items = value; } } } 不知道你说的是不是这个意思:)
3个月前   回答者:TerryLee - 老鸟四级
评论
   您需要登录以后才能回答!
 

我要提问

我的问题


快到期问题

> 问题排行榜

相关内容

相关链接