CSharp学习笔记 (一)序列化类实例

2021年11月10日 1点热度 0条评论 来源: hangzhouhao

XmlSerializer, DataContractSerializer 和 BinaryFormatter区别与用法分析:http://www.cnblogs.com/nankezhishi/archive/2012/05/12/serializationcompare.html

1. DataContractSerializer :所有类均可实例化,不需要加可序列化关键词

(1)序列化:

            try
            {
                fs = new FileStream(文件名, FileMode.Create);
                ser = new DataContractSerializer(typeof(类名));
                ser.WriteObject(fs, 类实例变量);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

(2)反序列化:

            FileStream fs = new FileStream(文件名, FileMode.Open);
            XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser = new DataContractSerializer(typeof(类名));
            类名 类实例名 = (类名)ser.ReadObject(reader, true);
            psidentify = new 类名(类实例名);    //array to List
            reader.Close();
            fs.Close();

2. BinaryFormatter:类定义前需加关键词[Serializable],文件小,内容不易解读

(1)序列化:

                fs = new FileStream(文件名, FileMode.Create);
                try
                {
                    formatter.Serialize(fs, 类实例名);
                }
                catch (SerializationException e)
                {
                    Console.WriteLine("Failed to serialize. Reason: " + e.Message);
                    throw;
                }
                finally
                {
                    fs.Close();
                }

(2)反序列化:

                fs = new FileStream(文件名, FileMode.Open);
                try
                {
                    类实例名 = (类名)formatter.Deserialize(fs);
                }
                catch (SerializationException e)
                {
                    Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
                    throw;
                }
                finally
                {
                    fs.Close();
                }

    原文作者:hangzhouhao
    原文地址: https://blog.csdn.net/hangzhouhao/article/details/44935959
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。