簡體   English   中英

如何序列化嵌套在類中的實例列表?

[英]How to Serialise a List of instance nested within a class?

我正在嘗試通過序列化將類保存到文件中,它可以完全正常工作,但是無法序列化嵌套類。

我的類假設用一個名稱,描述...表示一個Task,它可以由子任務組成,該子任務由任務列表表示

我已經嘗試在我的列表之前寫[Serializable],就像在這里解釋: 在c#中序列化嵌套類?

但我收到此錯誤:“屬性'Serializable'在此聲明類型上無效。僅在聲明上有效。”

[Serializable()]
public class t_Task
{
   private string nom;
   private string description;
   [Serializable]
   List<t_Task> subTask;
}

請問如何讓列表中的所有班級也序列化?

編輯:我正在使用以下方法進行序列化: http : //blog.danskingdom.com/saving-and-loading-ac-objects-data-to-an-xml-json-or-binary-file/

public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(stream, objectToWrite);
    }
}

然后我用接近這個的方法來稱呼它

public void Save()
        {
            GesionBinaryFileIO.WriteToBinaryFile<t_Task>(PathToFile, this);
        }

[Serializeable]不允許用於字段/屬性,僅需要放在類中。 您的類應可序列化,如下所示:

[Serializable()]
public class t_Task
{
   private string nom;
   private string description;
   List<t_Task> subTask; // Removed the [Serializeable] attribute
}

重要的是要注意, List<t_Task>不是嵌套類(它只是常規類字段),因此您所引用的鏈接實際上與您的問題無關。

[Serializable]是一種比較古老的標記序列化方法。 我將參考有關SerializeableAttributeMicrosoft文檔 ,以了解您的代碼如何工作。

這是基於我鏈接的Microsoft文章的示例:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleOne
{
    [Serializable()]
    public class t_Task
    {
        private string nom = "test"; // Added for test data.
        private string description = "desc"; // Added for test data
        List<t_Task> subTask = new List<t_Task>();

        public void AddTask()
        {
            this.subTask.Add(new t_Task());
        }

        public override string ToString()
            => $"{nom}-{description}-{subTask?.Count}";
    }

    class Program
    {
        static void Main(string[] args)
        {
            var task = new t_Task()
            {

            };

            task.AddTask();
            task.AddTask();

            // Opens a file and serializes the object into it in binary format.
            Stream stream = File.Open("data.xml", FileMode.Create);

            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, task);
            stream.Close();

            //Empties obj.
            task = null;

            //Opens file "data.xml" and deserializes the object from it.
            stream = File.Open("data.xml", FileMode.Open);
            formatter = new BinaryFormatter();

            //formatter = new BinaryFormatter();

            task = (t_Task)formatter.Deserialize(stream);
            stream.Close();

            Console.WriteLine($"{task}");
            Console.ReadLine();
        }
    }
}

注意:.NET中還有許多其他的現代化序列化方法。 也許也值得一讀。 但是,如果您只對簡單的二進制格式感興趣,那么以上信息就足夠了。

暫無
暫無

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

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