zoukankan      html  css  js  c++  java
  • 序列化和反序列化问题

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    namespace BinarySerializableExample
    {
        [Serializable]//序列化
            //序列化的两个功能是:1:将对象的状态存储在媒体中,便于创建对象的精确的副本
            //2.通过值将对象从一个应用程序传送到另一个应用程序
        public class AuthUserEntry
        {
            private int accountId;
            private string accountName;
            public int AccountId
            {
                get
                {
                    return accountId;
                }
                set
                {
                    accountId = value;
                }
            }
            public string AccountName
            {
                get
                {
                    return accountName;
                }
                set
                {
                    accountName = value;
                }
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                AuthUserEntry ate = new AuthUserEntry();
                ate.AccountId = 21;
                ate.AccountName = "LiangShuai";
                IFormatter formatter = new BinaryFormatter();//序列化到一个二进制的文件.bin中
                Stream stream = new FileStream("UserInfo.bin",FileMode.Create,FileAccess.Write,FileShare.None);
                formatter.Serialize(stream,ate);
                stream.Close();
                //反序列化时要首先创建用于读取的流和格式化接口,然后用格式化接口反序列化该对象
                stream = new FileStream("UserInfo.bin",FileMode.Open,FileAccess.Read,FileShare.Read);
                AuthUserEntry auth = (AuthUserEntry)formatter.Deserialize(stream);
                stream.Close();
                Console.WriteLine("ID is{0}",auth.AccountId);
                Console.WriteLine("Name is {0}",auth.AccountName);
                Console.ReadKey();

            }
        }
    }

    未经许可禁止转载本博客内容
  • 相关阅读:
    RC4加密
    树莓派3B+学习笔记:13、不间断会话服务screen
    树莓派3B+学习笔记:12、安装FireFox浏览器
    树莓派3B+学习笔记:11、查看硬件信息
    树莓派3B+学习笔记:10、使用SSH连接树莓派
    树莓派3B+学习笔记:9、更改软件源
    树莓派3B+学习笔记:8、安装MySQL
    树莓派3B+学习笔记:7、挂载exfat格式U盘和NTFS格式移动硬盘
    树莓派3B+学习笔记:6、安装TeamViewer
    树莓派3B+学习笔记:5、安装vim
  • 原文地址:https://www.cnblogs.com/liangshuai/p/2229281.html
Copyright © 2011-2022 走看看