代码改变世界

C# 中的序列化与反序列化

2011-04-25 12:33  音乐让我说  阅读(458)  评论(0编辑  收藏  举报

Demo1

using System;
using System.IO;
using System.Xml.Serialization;

/*
重点:由于Serializable标记了[AttributeUsage(Inherited = false)],那么被它标记的类A也就有了可以被序列化的能力,但继承自类A的类如果不加[Serializable],也就没有序列化的能力。
 参考资料:http://www.cnblogs.com/qqflying/archive/2008/01/13/1037262.html
 */


namespace WebUI
{
    public partial class TestSerializable : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                Person s = new Person() { ID = 1001, Name = "张三", Age = 18 };
                FileStream fsToWrite = new FileStream(Server.MapPath("~/被序列化的对象.xml" /* 或者是txt文件 */), FileMode.Create, FileAccess.Write);
                //BinaryFormatter bfToWrite = new BinaryFormatter();
                //bfToWrite.Serialize(fsToWrite, s);
                //或者使用XML序列化,且它还不需要标记Serializable
,但是它不能序列化 IList<Person>                XmlSerializer xs = new XmlSerializer(typeof(Person));
                xs.Serialize(fsToWrite, s);

                fsToWrite.Dispose();
                fsToWrite.Close();
                this.ltMessage.Text = "序列化成功!";
            }
        }

        protected void btnGetDataFromSerialization_Click(object sender, EventArgs e)
        {
            FileStream fsToRead = new FileStream(Server.MapPath("~/被序列化的对象.xml" /* 或者是txt文件 */), FileMode.Open, FileAccess.Read, FileShare.Read);
            //BinaryFormatter bfToRead = new BinaryFormatter();
            //Person s = (Person)bfToRead.Deserialize(fsToRead);

            XmlSerializer xs = new XmlSerializer(typeof(Person));
            Person s = (Person)xs.Deserialize(fsToRead);

            fsToRead.Dispose();
            fsToRead.Close();
            this.ltMessage.Text = "反序列化后,得到的姓名为:" + s.Name + ",ID:" + s.ID + ",年龄:" + s.Age;
        }
    }

    [Serializable]
    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }

        [NonSerialized]
        private int _age;

        public int Age
        {
            get
            {
                return _age;
            }
            set
            {
                _age = value;
            }
        }
    }

    public class Student : Person
    {

    }
}

Demo2

using System;
using System.Web;
using System.Reflection;

namespace WebUI
{
    public partial class TestSerializable2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                PeopleInHunan hunan = new PeopleInHunan();
                Type tpHunan = hunan.GetType();
                MethodInfo mi = tpHunan.GetMethod("Introduction");
                if (mi != null)
                {
                    object[] cnObjs = mi.GetCustomAttributes(typeof(ChineseNameAttribute), true);
                    if (cnObjs.Length > 0)
                    {
                        ChineseNameAttribute cn = (ChineseNameAttribute)cnObjs[0];
                        Response.Write("存在特性!");
                    }
                    else
                    {
                        Response.Write("不存在特性!");
                    }
                }
                else
                {
                    Response.Write("Introduction方法不存在!");
                }

                //测试的时候试试把ChineseNameAttribute标记的属性Inherited = false
            }
        }
    }

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ChineseNameAttribute : Attribute
    {
        public ChineseNameAttribute()
        {
            HttpContext.Current.Response.Write("LoginFilterAttribute的无参构造函数初始化完成!");
        }

        public ChineseNameAttribute(string name)
        {
            Name = name;
            HttpContext.Current.Response.Write("LoginFilterAttribute的有参构造函数初始化完成!姓名:" + name);
        }

        public string Name { get; set; }
    }


    public class Chinese
    {

        public Chinese(string name)
        {
            Name = name;
        }

        public string Name 
        { 
            get; set; 
        }

        [ChineseName]
        public virtual void Introduction()
        {
            HttpContext.Current.Response.Write("我的中文名字叫:" + Name);
        }


        [ChineseName("刘德华")]
        public virtual void SayHello(string name)
        {
            HttpContext.Current.Response.Write(name + ",您吃饭了吗?");
        }
    }

    public class PeopleInHunan : Chinese
    {
        public PeopleInHunan() : base("湖南人")
        {

        }

        public override void Introduction()
        {
            HttpContext.Current.Response.Write("我的湖南名字叫:" + Name);
        }
    }
}

Demo3

using System;
using System.Web;
using System.Reflection;

namespace WebUI
{
    public partial class TestSerializable3 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PeopleInHunan hunan = new PeopleInHunan();
                Type tpHunan = hunan.GetType();
                Object[] attrs = tpHunan.GetCustomAttributes(typeof(ChineseNameAttribute), true);
                if (attrs != null && attrs.Length > 0)
                {
                    ChineseNameAttribute cn = (ChineseNameAttribute)attrs[0];
                    Response.Write("存在特性!Name:" + cn.Name);
                }
                else
                {
                    Response.Write("不存在特性!");
                }
                //测试的时候试试把ChineseNameAttribute标记的属性Inherited = false
            }
        }
        
    }

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ChineseNameAttribute : Attribute
    {
        public ChineseNameAttribute()
        {
            HttpContext.Current.Response.Write("LoginFilterAttribute的无参构造函数初始化完成!");
        }

        public ChineseNameAttribute(string name)
        {
            Name = name;
            HttpContext.Current.Response.Write("LoginFilterAttribute的有参构造函数初始化完成!姓名:" + name);
        }

        public string Name { get; set; }
    }


    [ChineseName(Name = "中国人")]
    public class Chinese
    {

        public Chinese(string name)
        {
            Name = name;
        }

        public string Name
        {
            get;
            set;
        }

        [ChineseName]
        public virtual void Introduction()
        {
            HttpContext.Current.Response.Write("我的中文名字叫:" + Name);
        }


        [ChineseNameAttribute("刘德华")]
        public virtual void SayHello(string name)
        {
            HttpContext.Current.Response.Write(name + ",您吃饭了吗?");
        }


    }

    public class PeopleInHunan : Chinese
    {
        public PeopleInHunan()
            : base("湖南人")
        {

        }
    }
}

 

我的后一篇:http://www.cnblogs.com/Music/archive/2012/06/14/about-c-sharp-serialize-and-deserialize-2.html

 

谢谢浏览!