Home > Java > javaTutorial > body text

Serialization and deserialization of c#

黄舟
Release: 2016-12-27 13:56:48
Original
1144 people have browsed it

Serialization and deserialization

This can directly convert the object into binary for storage and communication;
Add [Serializable] before the class that needs to be serialized, and use the BinaryFormatter class to operate;

<code class="language-c# hljs cs">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 序列化与反序列化
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student("刘备",28,&#39;男&#39;);
            Student stu2;
            string file = @"E:\code\test\test1.txt";
            using (FileStream fsWriter=new FileStream(file,FileMode.OpenOrCreate,FileAccess.Write))
            {
                //下面对stu进行序列化;
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fsWriter, stu);
            }
            using (FileStream fsReader=new FileStream(file,FileMode.Open,FileAccess.Read))
            {
                //下面进行反序列话;
                BinaryFormatter bf = new BinaryFormatter();
                stu2 = (Student)bf.Deserialize(fsReader);
            }
            Console.WriteLine("{0}今年{1}岁,是个{2}生",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;
        }
    }
}
</code>
Copy after login

The above is the content of serialization and deserialization of c#. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!