簡體   English   中英

如何序列化通用列表?

[英]How to serialise generic list?

我有一個通用的employeessupervisors名單

List<Employee> employees = new List<Employee>();
List<Supervisor> supervisors = new List<Supervisor>(); 

他們都是我標記為[Serializable]employee類別的一部分

我可以將這兩個列表放到另一個列表中,以便更輕松地進行序列化嗎?

我看過序列化教程,但它們僅指定一個或更少的通用列表。

我已經提供了一個模板,我想單擊“保存”按鈕並完成序列化過程,最好將兩個列表都放入一個更大的列表中。

private void btnSave_Click(object sender, EventArgs e)
{
     FileStream outFile;
     BinaryFormatter bFormatter = new BinaryFormatter();
}

您實際上可以將兩個列表序列化為一個流:

using (FileStream fs = new FileStream(..., FileMode.OpenOrCreate)) {
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(fs, employees);
    bf.Serialize(fs, supervisors);
}

BinaryFormatter為數據塊添加元數據前綴,這顯然也使它可以將數據連接到一個文件。 為了回讀supervisors您必須先加載其他列表。 由於列表不是固定長度的記錄,因此當您重寫第一個列表並將其丟失在孤立數據之后或覆蓋其中的一部分時,第二個列表可能變得不可用。

由於有太多的事情可以阻止它起作用,因此很容易為倍數創建“ holder”或容器類:

[Serializable()]
public class BFHolder
{
    public List<Employee> employees { get; set; }
    public List<Supervisor> supervisors { get; set; }   
    public BFHolder()
    {
    }
}

反序列化后,可以根據需要拉出列表。

還有一個更好的選擇是ProtoBuf-Net (向下滾動至自述)。 除了比BinaryFormatter更快並創建較小的輸出外,它還包括將多個對象序列化為一個流的方法。

using (FileStream fs = new FileStream(..., FileMode.OpenOrCreate)) {
    Serializer.SerializeWithLengthPrefix<List<Employee>>(fs, employees,
                    PrefixStyle.Base128);
    Serializer.SerializeWithLengthPrefix<List<Supervisor>>(fs, supervisors,
                    PrefixStyle.Base128);
}

您可以將此列表放在另一個類容器中並對其進行序列化/反序列化。

[Serializable]
public class Container 
{
     public List<Employee> employees = new List<Employee>();
     public List<Supervisor> supervisors = new List<Supervisor>();
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM