c#中对象序列化为二进制流

首先创建一个对象

 [Serializable]  //一个对象要实现序列化,用特征类[Serializeable]来标示
    class SerilalizeObject
    {
        public int ID { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        [NonSerialized]//当不需要序列化时,用特征类[NoSerialize]来标示
        public string NoSerialize;
    }
}

代码实现

 static void Main(string[] args)
        {
            SerilalizeObj();

            DeSerilalize();

            Console.ReadKey();

        }

        private static void DeSerilalize()
        {
            SerilalizeObject NoSerilalize = new SerilalizeObject();

            FileStream OpenStream = new FileStream("test.txt", FileMode.Open);

            BinaryFormatter Noserilaze = new BinaryFormatter();
            try
            {
                SerilalizeObject DeSerilalizeObj = (SerilalizeObject)Noserilaze.Deserialize(OpenStream);

                 Console.WriteLine("反序列化结果为:{0}-{1}-{2}", DeSerilalizeObj.ID,DeSerilalizeObj.UserName,DeSerilalizeObj.Password);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                OpenStream.Close();
            }
           
        }
        /// <summary>
        /// 序列化一个对象
        /// </summary>
        private static void SerilalizeObj()
        {
            SerilalizeObject obj = new SerilalizeObject { ID = 1, Password = "mima", UserName = "userName", NoSerialize = "No" };

            FileStream fs = new FileStream("test.txt", FileMode.Create);
            ///序列化二进制
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, obj);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                fs.Close();
            }
        }

运行结果

对于反序列化当然还是原样输出了创建的对象

对于序列化我们打开文本文件,是乱码,什么都看打不开

BinaryFormater 比ProtoBuf.net(第三方的)要损耗性能

posted @ 2013-06-16 21:03  xinyebs  阅读(1240)  评论(0编辑  收藏  举报