C# 二进制序列化和反序列化的具体实现

Isleta ·
更新时间:2024-09-20
· 1662 次阅读

.NET框架提供了两种种串行化的方式:

1、是使用BinaryFormatter进行串行化;

2、使用XmlSerializer进行串行化。

第一种方式提供了一个简单的二进制数据流以及某些附加的类型信息,而第二种将数据流格式化为XML存储。可以使用[Serializable]属性将类标志为可序列化的。如果某个类的元素不想被序列化,1、可以使用[NonSerialized]属性来标志,2、可以使用[XmlIgnore]来标志。

序列化意思指的是把对象的当前状态进行持久化,一个对象的状态在面向对象的程序中是由属性表示的,所以序列化类的时候是从属性读取值以某种格式保存下来,而类的成员函数不会被序列化,.net存在几种默认提供的序列化,二进制序列化,xml和json序列化会序列化所有的实例共有属性。

这里简单介绍:BinaryFormatter以二进制格式序列化和反序列化对象。

BinaryFormatte序列化:将对象转化成二进制,BinaryFormatte反序列化就是将二进制转化为对象;

命名空间: System.Runtime.Serialization.Formatters;

最常用的两个方法:

Deserialize(Stream)     将指定的流反序列化成对象

Serialize(Stream, Object)     将对象序列化到给定的流

两个常用的属性:

Serializable     表示可以被序列化

NonSerializable     屏蔽被序列化

 简单示例: namespace Model {     [Serializable]    public class Config    {            [NonSerialized]  // 表示下面这个age字段不进行序列化        private int age{ get; set; }        public string Language { get; set; }        public bool IsAutoBackup { get; set; }        public int BackupTimeForHour { get; set; }        public string LastTimeRestoreDBFile { get; set; }        public DateTime? LastAutoBackupDateTime { get; set;}        public bool IsSupportHis { get; set; }        //序列化 fileName:文件地址        public void SaveTo(string fileName)        {            using (MemoryStream ms = new MemoryStream())            {                BinaryFormatter formatter = new BinaryFormatter();                formatter.Serialize(ms, this);                File.WriteAllBytes(fileName, ms.ToArray());            }        }        //反序列化        public static DSConfig LoadFromFile(string fileName)        {            try            {                if (!File.Exists(fileName))                    return null;                else                {                    byte[] buff = File.ReadAllBytes(fileName);                    using (MemoryStream ms = new MemoryStream(buff))                    {                        BinaryFormatter formatter = new BinaryFormatter();                        return (DSConfig)formatter.Deserialize(ms);                    }                }            }            catch (Exception ex)            {            }            return null;        }    } }

调用示例

private const string CONFIGNAME = "b1b4af87-1870-11e9-a31b-8cec4b4fece0.cfg"; public static string ConfigName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Viewer",CONFIGNAME); Config config = Config.LoadFromFile(ConfigName); //对Config类里面参数赋值后保存 Config.SaveTo(ConfigName);

BinaryFormatte序列化,示例二:

using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace Binaryformats { internal class Program { private static void Main(string[] args) { Person p = new Person(); p.Sex = 1; p.Age = 21; p.Name = "dfr"; byte[] serBytes = BinaryFormat.Serialize(p); //序列化 Person pp = (Person) BinaryFormat.Deserialize(serBytes); //反序列化,object类转化成自己定义的 Console.WriteLine(pp.Name); Console.ReadLine(); } [Serializable] private class Person //用Serializable做了标记,标识可以被序列化 { private int _age; [NonSerialized] private string _name; //用NonSerialized做了标记,标识该字段屏蔽序列化 private int _sex; public string Name { get { return _name; } set { _name = value; } } public int Sex { get { return _sex; } set { _sex = value; } } public int Age { get { return _sex; } set { _sex = value; } } } } public class BinaryFormat { public static byte[] Serialize(Object Urobject) //序列化 返回byte[]类型 { BinaryFormatter bf = new BinaryFormatter(); MemoryStream memory = new MemoryStream();//使用using 可以避免忘记释放 bf.Serialize(memory, Urobject); byte[] bytes = memory.GetBuffer(); memory.Close(); return bytes; //或者采用方法: using (MemoryStream ms = new MemoryStream(buff)) { } } public static object Deserialize(byte[] bytes) //反序列化,返回object类型的 { BinaryFormatter bf = new BinaryFormatter(); MemoryStream memory = new MemoryStream(bytes); object ss = bf.Deserialize(memory); memory.Close(); return ss; } } }

到此这篇关于C# 二进制序列化和反序列化的具体实现的文章就介绍到这了,更多相关C# 二进制序列化和反序列化内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



C# 进制 序列化 二进制

需要 登录 后方可回复, 如果你还没有账号请 注册新账号