>  기사  >  Java  >  C#의 직렬화 및 역직렬화

C#의 직렬화 및 역직렬화

黄舟
黄舟원래의
2016-12-27 13:56:481111검색

직렬화 및 역직렬화

이는 저장 및 통신을 위해 객체를 바이너리로 직접 변환할 수 있습니다.
직렬화해야 하는 클래스 앞에 [Serialized]를 추가하고 BinaryFormatter 클래스를 사용하여 작동합니다.

<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>

위 내용은 C#의 직렬화, 역직렬화 내용입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.