不连数据库的方法
using System;
using System.IO;
using System.Xml.Serialization;
namespace Serializer
{
[Serializable]
public class Course
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _description;
[XmlIgnore()]
public string Description
{
get { return _description; }
set { _description = value; }
}
public Course()
{ }
public Course(string name, string description)
{
_name = name;
_description = description;
}
}
[Serializable]
public class Person
{
private string _name;
private string _sex;
private int _age;
public Course[] courses;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Sex
{
get { return _sex; }
set { _sex = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
public Person()
{ }
public Person(string name)
{
_name = name;
_sex = "男";
_age = 23;
}
}
public class XmlSerialize
{
//序列化
public void Serialize()
{
Person student = new Person("Soil");
student.courses = new Course[3];
student.courses[0] = new Course("英语", "交流工具");
student.courses[1] = new Course("数学", "自然科学");
student.courses[2] = new Course("物理", "自然科学");
XmlSerializer xs = new XmlSerializer(typeof(Person));
FileStream fs = new FileStream("student.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
xs.Serialize(fs, student);
fs.Close();
}
//反序列化
public void Deserialize()
{
XmlSerializer xs = new XmlSerializer(typeof(Person));
FileStream fs = new FileStream("student.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Person student = (Person)xs.Deserialize(fs);
fs.Close();
Console.WriteLine(student.Name);
Console.WriteLine(student.Sex);
Console.WriteLine(student.Age.ToString());
Console.WriteLine(student.courses[0].Name);
Console.WriteLine(student.courses[1].Name);
Console.WriteLine(student.courses[2].Name);
Console.ReadLine();
}
}
}