C # serialization and deserialization,

Source: Internet
Author: User

C # serialization and deserialization,
Serialization and deserialization

This can directly convert the object to binary for storage and communication;
Add [Serializable] to the class to be serialized and use the BinaryFormatter class for operations;

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. IO; using System. runtime. serialization. formatters. binary; namespace serialization and deserialization {class Program {static void Main (string [] args) {Student stu = new Student ("Liu Bei", 28, 'mal '); student stu2; string file = @ "E: \ code \ test \ test1.txt"; using (FileStream fsWriter = new FileStream (file, FileMode. openOrCreate, FileAccess. write) {// stu serialization; BinaryFormatter bf = new BinaryFormatter (); bf. serialize (fsWriter, stu);} using (FileStream fsReader = new FileStream (file, FileMode. open, FileAccess. read) {// The Reverse Sequence below; BinaryFormatter bf = new BinaryFormatter (); stu2 = (Student) bf. deserialize (fsReader);} Console. writeLine ("{0} {1} years old, is a {2} student", stu2.Name, stu2.Age, stu2.Gender); Console. readKey () ;}} [Serializable] public class Student {private string _ name; public string Name {get {return _ name ;}set {_ name = value ;}} private int _ age; public int Age {get {return _ age;} set {_ age = value ;}} private char _ gender; public char Gender {get {return _ gender;} set {_ gender = value ;}} public Student (string name, int age, char gender) {Name = name; age = age; Gender = gender ;}}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.