繁体   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