首页 新闻 会员 周边

包含泛型集合的类二进制序列化方法

0
悬赏园豆:200 [已关闭问题]
<P>&nbsp;</P>
问题补充: 现在有一个回答了,没细看,这几天太忙了,没时间验证,过2天验证吧。我的目的是做一个可以对各种类进行各种序列化的内裤。答案1或许可以(没验证)但需要对集合类型的数据类型的属性加上XmlArray和XmlArrayItem两个Attribute的设置,这设置不知道能不能在类库中实现,为客户端降低编码的复杂度。
衡茜的主页 衡茜 | 初学一级 | 园豆:2
提问于:2008-06-23 11:14
< >
分享
其他回答(1)
0
[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特性标志为可序列化的。
玉开 | 园豆:8822 (大侠五级) | 2008-06-23 11:31
0
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; } } } 不知道你说的是不是这个意思:)
TerryLee | 园豆:3300 (老鸟四级) | 2008-06-23 11:33
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册