序列化和反序列化的例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication2008
{
  
    class Interface_Test{
        /// <summary>
        /// 将序列化后的信息转换为字符串
        /// </summary>
        /// <param name="date">要序列化的对象</param>
        /// <param name="path">文件路径</param>
        static void Serialize(object date, string path)
        {
            if(File.Exists(path))
                File.Delete(path);
            using(FileStream fs=new FileStream(path, FileMode.Create, FileAccess.Write)){
                BinaryFormatter format = new BinaryFormatter();
                format.Serialize(fs, date);
            }


        }
        /// <summary>
        /// 反序列化数据
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>object对象</returns>
        static object Deserialize(string path)
        {
            if(!File.Exists(path))
                return null;
         
            using(FileStream fs=new FileStream(path, FileMode.Open, FileAccess.Read)){
                BinaryFormatter format = new BinaryFormatter();
               return format.Deserialize(fs);
            }

        }

 

       static void Main()
        {
            People P = new People();
            Serialize(P, @"E://test.txt");
            object obj = Deserialize(@"E://test.txt");
            People P2 = obj as People;
            if (obj != null)
            {              
                Console.WriteLine(P2.Name);
            }
           
            
           
           
        }


    }
    [Serializable]
    public class People
    {
        public string Name="广东小子";
        public string Sex;
        private int _Age=23;
        public int Age
        {
            get { return _Age; }
            set { _Age = value; }
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值