对象序列化与反序列化

View Code

要在序列化的类上加一个特性:    [Serializable]

Student 类
[Serializable]
    class Student
    {
        public Student(string name,int age)
        {
            this.name = name;
            this.age = age;
        }

        private Dog dog;

        internal Dog Dog
        {
            get { return dog; }
            set { dog = value; }
        }

        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        [Obsolete("这个方法是已经过时的方法,请使用SayHello代替")]
        public void SayHi()
        {
            Console.WriteLine("姓名:{0},年龄:{1}",name,age);
        }
    }
序列化
            Student stu = new Student("拉登", 18);
            Student stu1 = new Student("布什", 18);
            Student stu2 = new Student("萨达姆", 18);
            List<Student> students = new List<Student>();
            students.Add(stu);
            students.Add(stu1);
            students.Add(stu2);

            //序列化
            using (FileStream fs = new FileStream("stus", FileMode.Create))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, students);
            }
反序列化
            using (FileStream fs = new FileStream("stus", FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                List<Student> stus = bf.Deserialize(fs) as List<Student>;
                if (stus != null)
                {
                    foreach (Student item in stus)
                    {
                        item.SayHi();
                    }
                }
            }

 

转载于:https://www.cnblogs.com/hejinyang/archive/2012/12/09/2810032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值