首页 > 学院 > 开发设计 > 正文

序列化、反序列化的使用

2019-11-17 03:14:25
字体:
来源:转载
供稿:网友
序列化、反序列化的使用

调用:

using System;namespace ConsoleApp_Serializable{    class PRogram    {        static void Main(string[] args)        {            Person mike = new Person() { Age = 21, Name = "Mike" };            mike.NameChanged += mike_NameChanged;            BinarySerializer.SerializeToFile(mike, @"c:/", "person.txt");            Person p = BinarySerializer.DeserializeFromFile<Person>(@"c:/person.txt");            p.Name = "rose";            Console.WriteLine(p.Name);            Console.WriteLine(p.Age.ToString());            Console.ReadKey();        }        static void mike_NameChanged(object sender, EventArgs e)        {            Console.WriteLine("Name Changed !");        }    }    [Serializable]    class Person    {        private string name;        public int Age { get; set; }        public string Name        {            get { return name; }            set            {                if (NameChanged != null)                {                    NameChanged(this, null);                }                name = value;            }        }        //事件往往是不需要序列化的,反序列化的环境和序列化的环境往往不一致,这就失去了将事件序列化的意义。        [field: NonSerialized]        public event EventHandler NameChanged;    }}
工具类:
using System.IO;using System.Runtime.Serialization.Formatters.Binary;namespace ConsoleApp_Serializable{    public class BinarySerializer    {        /// <summary>        /// 将类型序列化为字符串        /// </summary>        public static string Serialize<T>(T t)        {            using (MemoryStream stream = new MemoryStream())            {                BinaryFormatter formatter = new BinaryFormatter();                formatter.Serialize(stream, t);                return System.Text.Encoding.UTF8.GetString(stream.ToArray());            }        }        /// <summary>        /// 将类型序列化为文件        /// </summary>        public static void SerializeToFile<T>(T t, string path, string fullname)        {            if (!Directory.Exists(path))            {                Directory.CreateDirectory(path);            }            string fullPath = string.Format(@"{0}/{1}", path, fullname);            using (FileStream stream = new FileStream(fullPath, FileMode.OpenOrCreate))            {                BinaryFormatter formatter = new BinaryFormatter();                formatter.Serialize(stream, t);                stream.Flush();            }        }        /// <summary>        /// 将字符串反序列化为类型        /// </summary>        public static TResult Deserialize<TResult>(string s) where TResult : class        {            byte[] bs = System.Text.Encoding.UTF8.GetBytes(s);            using (MemoryStream stream = new MemoryStream(bs))            {                BinaryFormatter formatter = new BinaryFormatter();                return formatter.Deserialize(stream) as TResult;            }        }        /// <summary>        /// 将文件反序列化为类型        /// </summary>        public static TResult DeserializeFromFile<TResult>(string path) where TResult : class        {            using (FileStream stream = new FileStream(path, FileMode.Open))            {                BinaryFormatter formatter = new BinaryFormatter();                return formatter.Deserialize(stream) as TResult;            }        }    }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表