之前常常在项目或案例上看到[Serializable]但是都以为是vs自带的标记或是什么便没有太在意.直到发现他是有固定存在位置时才认为他非比寻常.
就目前经验来说,[Serializable]的作用是将一笔数据序列化到文件中用来存储一段信息,防止关闭程序后数据丢失.(百度之后好像还有类似于标记的作用,如后续有用到再继续完善)
我的学习过程:1.新增一个类:
[Serializable] class Class1 {
public string DataTime { get; set; }
public string Cust { get; set; }
}
2在mainfron中实例化
var data = new Class1{
DataTime = cbo_date.Text,
Cust = cbo_cust.Text
};
List
personInfo.Add(data);//把实例化的数据放进personinfo
IFormatter formatter = new BinaryFormatter();//创建一个格式化程序的实例
if (!File.Exists(System.IO.Directory.GetCurrentDirectory() + "\\TestTxt.txt")) //创建一个文件流
{
Stream stream = new FileStream(System.IO.Directory.GetCurrentDirectory() + "\\TestTxt.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
foreach (Class1 per in personInfo)
{
formatter.Serialize(stream, per);
}
stream.Close();
}
else
{
Stream stream = new FileStream(System.IO.Directory.GetCurrentDirectory() + "\\TestTxt.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
foreach (Class1 per in personInfo)
{
formatter.Serialize(stream, per);
}
stream.Close();
}
Stream destream = new FileStream(System.IO.Directory.GetCurrentDirectory() + "\\TestTxt.txt", FileMode.Open,
FileAccess.Read, FileShare.Read);
var stillme = (Class1)formatter.Deserialize(destream);
MessageBox.Show(stillme.DisplayInfo());
destream.Close();
两个组数据
//var me = new Class1 //{ // Sno = "1215115231", // Name = "wuzhang", // Sex = "man", // Age = 22, // NoSerial = "不被序列化1", // Other = "\n" //}; //var he = new Class1 //{ // Sno = "1215115250", // Name = "wanggang", // Sex = "man", // Age = 21, // NoSerial = "不被序列化2", // Other = "\n" //}; //ListpersonInfo = new List();
//personInfo.Add(me);
//personInfo.Add(he);
////创建一个格式化程序的实例
//IFormatter formatter = new BinaryFormatter();
////创建一个文件流
//if (!File.Exists(System.IO.Directory.GetCurrentDirectory()+"\\TestTxt.txt"))
//{
// //FileStream fs1 = new FileStream("F:\\TestTxt.txt", FileMode.Create, FileAccess.Write);//创建写入文件
// Stream stream = new FileStream(System.IO.Directory.GetCurrentDirectory() + "\\TestTxt.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
// foreach (Class1 per in personInfo)
// {
// formatter.Serialize(stream, per);
// }
// stream.Close();
//}
//else
//{
// Stream stream = new FileStream(System.IO.Directory.GetCurrentDirectory() + "\\TestTxt.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
// foreach (Class1 per in personInfo)
// {
// formatter.Serialize(stream, per);
// }
// stream.Close();
//}
//Stream destream = new FileStream(System.IO.Directory.GetCurrentDirectory() + "\\TestTxt.txt", FileMode.Open,
//FileAccess.Read, FileShare.Read);
//var stillme = (Class1)formatter.Deserialize(destream);
//var stillme1 = (Class1)formatter.Deserialize(destream);
//MessageBox.Show(stillme.DisplayInfo());
//MessageBox.Show(stillme1.DisplayInfo());
//destream.Close();