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

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();
                }


你可能感兴趣的:(编程笔记)