简体   繁体   English

序列化包含数组和其他列表的列表

[英]Serialize A List That Contains Arrays & Other Lists

I have been trying to serialize a list that contains arrays and lists. 我一直在尝试序列化包含数组和列表的列表。

I have been trying different things but can't make it work. 我一直在尝试不同的方法,但无法使其正常工作。

I am getting this error: 我收到此错误:

Type 'EngineTest.MapData+tileDataBackground' in Assembly 'EngineTest, Version=1.0.0.0,
   Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Here is my MapData.cs that I am trying to serialize within a List. 这是我要在列表中序列化的MapData.cs。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EngineTest
{
[Serializable]
public class MapData
{
    public struct tileDataBackground
    {
        public int tileTextureX;
        public int tileTextureY;
    }

    public struct tileDataForeground
    {
        public int tileTextureX;
        public int tileTextureY;
    }

    public struct tileDataCollision
    {
        public bool tileCollision;
    }

    public tileDataBackground[,] tileBackground;
    public tileDataForeground[,] tileForeground;
    public tileDataCollision[,] tileCollision;


    public List<items> itemData = new List<items>();
    public List<functions> functionData = new List<functions>();
}
}

And here is the code to I am failed to serialize it with (Program.mapData is the list): 这是我无法对其进行序列化的代码(Program.mapData是列表):

        using (FileStream stream = File.Open("test.dat", FileMode.Create))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, Program.mapData);
            stream.Close();
        }

Can you point me out to the right direction here? 您能在这里指出我正确的方向吗?

Thanks in advance. 提前致谢。

You have to make all of the classes and sub classes as Serializable 您必须将所有类和子类设置为可序列化

[Serializable]
public class MapData
{
    [Serializable]
    public struct tileDataBackground
    {
        public int tileTextureX;
        public int tileTextureY;
    }
 ...

EDIT 编辑


As the comments note below types that you use in the fields of all your Serializable classes must them selves be Serializable. 如下面的注释所述,您在所有Seri​​alizable类的字段中使用的类型必须自己具有Seri​​alizable。 Types that are not used as part of the structure of the class or are used in a nonSerializable field do not need to be Serializable. 不用作类结构一部分或在nonSerializable字段中使用的类型不需要是可序列化的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM