悬赏分:200 浏览:303 次
|
[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特性标志为可序列化的。 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; } } } 不知道你说的是不是这个意思:) |