zoukankan      html  css  js  c++  java
  • C#--串行化与反串行化

    串行化是指存储和获取磁盘文件、内存或其他地方中的对象。在串行化时,所有的实例数据都保存到存储介质上,
    在取消串行化时,对象会被还原,且不能与其原实例区别开来。只需给类添加Serializable属性,就可以实现串行化实
    的成员。反串行化是串行化的逆过程,数据从存储介质中读取出来,并赋给类的实例变量。串行化能保存现有对象的所有状态,
    我想我们以前见过的一些游戏的角色账户中的dat文件应该就是被串行化的结果。我尝试了打开一个dat文件,果真得到了
    我需要的信息,一些角色的等级之类的信息果然在里面。

    串行化对象,需要先将对象加上[Serializable],如:

    [Serializable]
    public class user{}
    

     首先需要添加序列化命名空间:
    using System.Runtime.Serialization.Formatters.Binary;

    /// <summary>
    /// 写入磁盘
    /// </summary>
    /// <param name="obj">实例对象</param>
    /// <param name="file">保存的文件路径跟文件名称</param>
    private static void WriteBinary(object obj, string file)
    {
    
        using (Stream input = File.OpenWrite(HttpContext.Current.Server.MapPath(file)))
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(input, obj);
        }
    }
    
    /// <summary>
    /// 读出磁盘文件
    /// </summary>
    /// <param name="file">保存的文件路径跟文件名称</param>
    /// <returns>object对象</returns>
    public static object ReadBinary(string file)
    {
        using (Stream outPut = File.OpenRead(HttpContext.Current.Server.MapPath(file)))
        {
            BinaryFormatter bf = new BinaryFormatter();
            object user = bf.Deserialize(outPut);
            if (user != null)
            {
                return user;
            }
        }
        return null;
    }
    

     实例应用:

    protected void Page_Load(object sender, EventArgs e)
    {
        //.dat文件,这种文件是纯文本,没有数据属性结构方面的信息,可以用记事本等文本工具打开
        WriteBinary(new user()
        {
            id = 1,
            title = "贵源网络",
            url = "gzmsg.com",
            co = "软件开发",
            des="描述"
        }, "~/upload/data/user.dat");
        user user = ReadBinary("~/upload/data/user.dat") as user;
        Response.Write(user.des);   //描述
    }
    [Serializable]
    public class user
    {
        public int id { get; set; }
        public string title { get; set; }
        public string url { get; set; }
        public string co { get; set; }
        public string des = string.Empty;
    }
    

     如果需要对部分字段序列化部分不序列化时,我们可以按照如下设置实现

    [Serializable]
    public class user
    {
        public int id { get; set; }
        public string title { get; set; }
        public string url { get; set; }
        public string co { get; set; }
        [NonSerialized]
        public string des = string.Empty;
    }
    
  • 相关阅读:
    C#Windows服务程序安装常见问题解决方法
    解决access 导出 excel 字段截断错误的问题
    MySQL创建方法错误:This function has none of DETERMINISTIC, NO SQL
    解决问题 “You don't have permission to access /index.html on this server.”
    无法枚举容器中的对象,访问被拒绝的解决方法
    php xml操作
    php 字符串截取函数
    PHP iconv 解决utf-8和gb2312编码转换问题
    IIS6,IIS7中查看w3wp进程
    Solaris设备管理
  • 原文地址:https://www.cnblogs.com/sntetwt/p/3530762.html
Copyright © 2011-2022 走看看