码迷,mamicode.com
首页 > Windows程序 > 详细

(转)C#.NET如何不序列化字段、属性

时间:2015-09-25 18:35:49      阅读:528      评论:0      收藏:0      [点我收藏+]

标签:

C#.NET如何不序列化字段、属性

  • 当我们使用公开属性以及公开字段时,都可以顺利的被序列化,

     

    01.[Serializable]
    02.public class MyClass
    03.{
    04.    public int ID;
    05. 
    06.    public string Address;
    07. 
    08.    private int _age;
    09. 
    10.    public string Name { get; set; }
    11. 
    12.    public int Age
    13.    {
    14.        get { return _age; }
    15.        set { _age = value; }
    16.    }
    17.}

    Xml序列化成档案后的结果就像下图:  

    技术分享  

    JSON  

    技术分享  

    bin,因为bin档案肉眼看不懂,所以用反序列化表示

     

    技术分享  

    但总是会有不想要存成档案的字段或属性

    JSON及XML 若是不想被序列化 "属性" 及 "字段" 使用以下Attribute:

    [System.Xml.Serialization.XmlIgnore] [System.Web.Script.Serialization.ScriptIgnore] BinaryFormatter 若是不想被序列化 "属性" 只要在相对应的 "字段" 使用以下:[NonSerialized] 看个例子:

    01.[Serializable]
    02.public class MyClass
    03.{
    04.    [NonSerialized]
    05.    public int ID;
    06. 
    07.    public string Address;
    08. 
    09.    [NonSerialized]
    10.    private int _age;
    11. 
    12.    public string Name { get; set; }
    13. 
    14.    [System.Xml.Serialization.XmlIgnore]
    15.    [System.Web.Script.Serialization.ScriptIgnore]
    16.    public int Age
    17.    {
    18.        get { return _age; }
    19.        set { _age = value; }
    20.    }
    21.}

    Xml序列化,忽略Age属性  

    技术分享  

    JSON序列化,忽略Age属性  

    技术分享  

    BinaryFormatter序列化忽略 Age属性 及 ID 字段  

    技术分享

(转)C#.NET如何不序列化字段、属性

标签:

原文地址:http://www.cnblogs.com/richard88/p/4838804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!