首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實作物件 XML 序列化與反序列化完整教學(上)

     編輯:關於C語言

待序列化的類別定義

定義 Person 與 Course 兩個類別,並標記可序列化屬性:

Person 類別

[Serializable]
public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public string Sex;
    public int Age = 31;
    public Course[] Courses;

    public Person() { }

    public Person(string Name)
    {
        name = Name;
        Sex = "男";
    }
}

Course 類別

[Serializable]
public class Course
{
    public string Name;
    [XmlIgnore]
    public string Description;

    public Course() { }

    public Course(string name, string description)
    {
        Name = name;
        Description = description;
    }
}

設計重點

  • [Serializable] 標記類別可序列化
  • [XmlIgnore] 排除不需序列化的欄位(如 Description)
  • 公開欄位與屬性皆會被序列化
  • 預設建構函式為反序列化所需
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved