LIST現在也支援序列化和反序列化了
阿新 • • 發佈:2019-02-03
namespace List可以被序列化
{
class Program
{
static void Main(string[] args)
{
SerializeNow();
DeSerializeNow();
XmlSerialize();
XmlDeserialize();
Console.ReadKey();
}
#region 二進位制序列化
public static voidSerializeNow()
{
People people = new People { Name = "zzl", Sex = "男" };
FileStream fileStream = new FileStream("c:\\temp.dat", FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fileStream, people);
fileStream.Close();
}
public static void DeSerializeNow()
{
People people = new People();
FileStream fileStream = new FileStream("c:\\temp.dat", FileMode.Open,
FileAccess.Read, FileShare.Read);
BinaryFormatter b = new BinaryFormatter();
people = b.Deserialize(fileStream) as People;
if (people != null) Console.WriteLine(people.Name.PadRight(10) + people.Sex);
fileStream.Close();
}
#endregion
#region XML序列化 (XML序列化不支援泛型。你需要自行序列化到陣列再複製到泛型集合)
public static void XmlSerialize()
{
List<People> peopleList = new List<People>
{
new People{Name = "張三", Sex = "男"},
new People{Name = "李四", Sex = "女"},
};
XmlSerializer xs = new XmlSerializer(typeof(List<People>));
Stream stream = new FileStream("c:\\zzl.XML", FileMode.Create,
FileAccess.Write, FileShare.Read);
xs.Serialize(stream, peopleList);
stream.Close();
}
public static void XmlDeserialize()
{
XmlSerializer xs = new XmlSerializer(typeof(List<People>));
Stream stream = new FileStream("C:\\zzl.XML", FileMode.Open,
FileAccess.Read, FileShare.Read);
List<People> peopleList = xs.Deserialize(stream) as List<People>;
if (peopleList != null) peopleList.ForEach(i =>
Console.WriteLine(i.Name.PadRight(10) + i.Sex));
stream.Close();
}
#endregion
}
/// <summary>
/// 人類
/// </summary>
[Serializable]
public class People
{
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性別
/// </summary>
public string Sex { get; set; }
}
}