在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using System.Runtime.Serialization;
namespace test2 { [Serializable] //标记person类可以被序列化,实际操作发现不加这个xml序列化也可以,但是binary序列化必须加 public class person { string _name=string.Empty; private byte _age=default(byte); string _grade=string.Empty; public person() { } public void print() { Console.WriteLine("name:{0}, age:{1}, grade: {2}", _name, _age, _grade); } public void set(string name, byte age, string grade) { _name = name; _age = age; _grade = grade; }
} class Serialize {
public static void Main(string[] args) { person aperson = new person(); aperson.set("whooffermeajob", 25, "master"); aperson.print(); FileStream fs = new FileStream("person.xml", FileMode.Create); XmlSerializer x = new XmlSerializer(typeof(person)); //xml序列化,浅序列化,只序列化public字段 x.Serialize(fs, aperson); fs.Close(); Console.Read();
FileStream tfs = new FileStream("person.xml", FileMode.Open); //反序列化,由于xml的浅序列化,所以反序列化出的对象部分数据丢失。 person t = (person)x.Deserialize(tfs); tfs.Close(); t.print(); Console.Read();
FileStream fs2 = new FileStream("person.bin", FileMode.Create); //Binary序列化,深序列化 IFormatter b = new BinaryFormatter(); b.Serialize(fs2, aperson); fs2.Close(); Console.Read(); }
} |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论