C#序列化与反序列化

1、序列化与反序列化

序列化:序列化是将对象的状态存储到特定存储介质的过程,也可以说是将对象状态转换为可保持或传输的格式的过程。

反序列化:反序列化则是从特定存储介质中将数据重新构建对象的过程。通过反序列化,可以将存储在文件上的对象信息读取,然后重新构建为对象。


2、案例说明

对于一个Windows应用程序来说,配置文件是非常重要的。本案例将使用序列化与反序列化、实现保存与加载用户的配置信息。

2.1 创建用户配置信息类,并在类上加上[Serializable]特性

/// <summary>
/// 用户配置信息类
/// </summary>
[Serializable]
public class UserProfile
{
    public string ProxyName = string.Empty;     //代理服务器地址
    public string ProxyPort = string.Empty;     //代理服务器端口
    public string ProxyUserId = string.Empty;   //登录用户名
    public string ProxyUserPwd = string.Empty;  //登录密码
}

序列化特性[Serializable]主要用来告诉系统,下面的类是可序列化的。如果需要序列化某个特定的对象,那么它的各个成员对象也必须是可序列化的。

2.2 创建配置信息管理业务类

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// 配置信息管理业务类
/// </summary>
public class ProfileHandler
{    
    public string fileName = "profile.bin";   //文件名
    
    /// <summary>
    /// 保存用户配置信息(序列化)
    /// </summary>
    public void Save(UserProfile profile)
    {
        FileStream fileStream = null;
        //定义一个文件流
        fileStream = new FileStream(fileName, FileMode.Create);
        //二进制方式
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fileStream, profile);
        fileStream.Close();
    }

    /// <summary>
    /// 获取用户配置信息(反序列化)
    /// </summary>
    /// <returns></returns>
    public UserProfile Load()
    {
        UserProfile profile = new UserProfile();
        FileStream fileStream = null;
        fileStream = new FileStream(fileName, FileMode.Open);
        BinaryFormatter bf = new BinaryFormatter();
        profile = (UserProfile)bf.Deserialize(fileStream);
        fileStream.Close();
        return profile;
    }
}

2.3 调用测试

static void Main(string[] args)
{
    UserProfile befProfile = new UserProfile();
    befProfile.ProxyName = "192.168.1.2";
    befProfile.ProxyPort = "3126";
    befProfile.ProxyUserId = "TomCruise";
    befProfile.ProxyUserPwd = "123456";
    //打印序列化前配置信息
    Console.WriteLine("服务器地址:{0}、服务器端口:{1}、用户名:{2}、密码:{3}", befProfile.ProxyName, befProfile.ProxyPort, befProfile.ProxyUserId, befProfile.ProxyUserPwd);
    ProfileHandler profileHandler = new ProfileHandler();
    //保存用户配置信息(序列化)
    profileHandler.Save(befProfile);
    //获取用户配置信息(反序列化)
    UserProfile aftProfile = profileHandler.Load();
    //打印序列化后,获取的配置信息
    Console.WriteLine("服务器地址:{0}、服务器端口:{1}、用户名:{2}、密码:{3}", aftProfile.ProxyName, aftProfile.ProxyPort, aftProfile.ProxyUserId, aftProfile.ProxyUserPwd);
    Console.Read();
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pan_junbiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值