https://www.php.cn/csharp-article-354650.html
namespace ConsoleApplication4
{
[ProtoContract]
public class Student
{
[ProtoMember(1)]
public int StudentId;
[ProtoMember(2)]
public string Name;
[ProtoMember(3)]
public string ClassName;
}
class Program
{
private const string TestPath = @"D:/1.txt";
static void Main(string[] args)
{
////////////////////////序列化//////////////////////////////
List<Student> stu = new List<Student>()
{
new Student(){
StudentId = 1,
Name = "zhangsan",
ClassName = "classOne"},
new Student(){StudentId = 2,
Name = "lisi",
ClassName = "classTwo"}
};
if (!File.Exists(TestPath))
{
FileStream fs = File.Create(TestPath, 1024, FileOptions.Asynchronous);
fs.Dispose();
}
Console.WriteLine("开始序列化并导出文件...");
using (Stream s = new FileStream(TestPath, FileMode.Open, FileAccess.ReadWrite))
{
Serializer.Serialize<List<Student>>(s, stu);
s.Close();
}
Console.WriteLine("序列化完毕");
//////////////////////反序列化////////////////////////////
Console.WriteLine("反序列化并输出...");
using (Stream s = new FileStream(TestPath, FileMode.Open))
{
List<Student> sl = Serializer.Deserialize<List<Student>>(s);
foreach (var student in sl)
{
Console.WriteLine("studentName:" + student.Name + "\r\n" +
"studentId:" + student.StudentId + "\r\n" +
"class Name:" + student.ClassName+"\r\n");
}
s.Close();
}
Console.Read();
}
}
}
网友评论