C# 序列化的方法
由于表达能力太差,直接上代码..
List<Serializationcs.Student> list = new List<Serializationcs.Student>();
list.Add(new Serializationcs.Student
{
Age=12,Name="test",No="1232"
});
list.Add(new Serializationcs.Student
{
Age = 34,
Name = "testtest",
No = "444"
});
Serializationcs serial = new Serializationcs();
serial.BinaryFormater(list);
serial.BinaryDESFormater();
public class Serializationcs
{
/// 序列化一个对象的状态持久化,把对象的信息保存到一些存储介质中,
/// 在需要时反序列化获取该对象的信息。主要应用需要序列化对象更能方便在在服务端和客户端之间传输///
/// 序列化已知有三种一.二进制,二XML序列化,三是SOAP序列化常用的是前两种.
///
//反序列化
/// <summary>
/// 二进制的反序列化
/// </summary>
public void BinaryDESFormater()
{
using (FileStream fs = new FileStream("test.bin", FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
List<Student> list = bf.Deserialize(fs) as List<Student>;
if (list != null)
{
for (int i = 0; i < list.Count; i++)
{
list[i].Say();
}
}
}
}
/// <summary>
/// 二进制的序列化
/// </summary>
/// <param name="list"></param>
public void BinaryFormater(List<Student> list)
{
//序列化
using (FileStream fs = new FileStream("test.bin", FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, list);
}
}
public void XmlFormatter(List<Student> list)
{
XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
using (Stream fs = new FileStream("xml.bat", FileMode.Create, FileAccess.Write, FileShare.None))
{
xs.Serialize(fs, list);
}
}
public void XmlDesFormatter()
{
XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
using (Stream fs = new FileStream("xml.bat", FileMode.Create, FileAccess.Write, FileShare.None))
{
List<Student> list = xs.Deserialize(fs) as List<Student>;
if (list != null)
{
for (int i = 0; i < list.Count; i++)
{
list[i].Say();
}
}
}
}
[Serializable]
public class Student
{
private string _name;
private string _no;
[NonSerialized]///可以排除序列化
private int _age;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string No
{
get { return _no; }
set { _no = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
public void Say()
{
Console.Write(Name, No);
}
}
}