简体   繁体   中英

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.

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):

        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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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