二进制序列化未初始化的struct数组

时间:2011-03-05 08:56:19

标签: c# serialization deserialization

我提供了一个模仿场景的最小代码。这是代码:

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


namespace Serialization
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] annotates = { "1", "2"};
            Guides[] g1 = new Guides[2];
            g1[0].comments = (string[])annotates.Clone();
            g1[1].comments = (string[])annotates.Clone();

            Guides[] g2 = new Guides[2];
            g2[0].comments = (string[])annotates.Clone();
            g2[1].comments = (string[])annotates.Clone();//to be commented later

            arrayStruct arrStr1 = new arrayStruct();
            arrStr1.guides_array = g1;

            arrayStruct arrStr2 = new arrayStruct();
            arrStr2.guides_array = g2;

            using (MoveSaver objSaver = new MoveSaver(@"C:\1.bin"))
            {
                MoveAndTime mv1 = new MoveAndTime();
                MoveAndTime mv2 = new MoveAndTime();
                mv1.MoveStruc = "1";
                mv1.timeHLd = DateTime.Now;
                mv1.arr = arrStr1;
                objSaver.SaveToFile(mv1);
                mv2.MoveStruc = "2";
                mv2.timeHLd = DateTime.Now;
                mv2.arr = arrStr2;
                objSaver.SaveToFile(mv2);
            }

            using (MoveSaver svrObj = new MoveSaver())
            {
                List<MoveAndTime> MVTobjs = svrObj.DeSerializeObject(@"C:\1.bin");
                foreach (MoveAndTime item in MVTobjs)
                {
                    Console.WriteLine(item.arr.guides_array[0].comments[0]);
                }
            }
        }

    }


    public class MoveSaver : IDisposable
    {
        public void Dispose()
        {
            if (fs != null)
            {
                fs.Close();
            }
        }
        FileStream fs;
        StreamWriter sw;
        public string filename { get; set; }
        public MoveSaver(string FileName)
        {
            this.filename = FileName;
            fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        }

        public MoveSaver()
        {

        }

        ~MoveSaver()
        {
            if (fs != null)
            {
                fs.Close();
            }

        }

        public List<MoveAndTime> DeSerializeObject(string filename)
        {
            List<MoveAndTime> retList = new List<MoveAndTime>();
            MoveAndTime objectToSerialize;
            Stream stream = File.Open(filename, FileMode.Open);
            BinaryFormatter bFormatter = new BinaryFormatter();
            while (stream.Position != stream.Length)
            {
                objectToSerialize = (MoveAndTime)bFormatter.Deserialize(stream);
                retList.Add(objectToSerialize);
            }
            stream.Close();
            return retList;
        }


        public bool SaveToFile(MoveAndTime moveTime)
        {
            try
            {
                BinaryFormatter bformatter = new BinaryFormatter();
                bformatter.Serialize(fs, moveTime);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }

    [Serializable]
    public struct MoveAndTime
    {
        public string MoveStruc;
        public DateTime timeHLd;
        public arrayStruct arr;
    }

    [Serializable]
    public struct arrayStruct
    { 
        public Guides[] guides_array;
    }

    [Serializable]
    public struct Guides
    {
        public string[] comments;
        public string name;
    }
}

在此代码中,struct包含多个结构,其中一个结构包含一个数组。尝试代码并且它编译得很好,但在实际场景中,整个数组没有填充,因此会有其他数组元素未指定。要查看此效果(在行动!),请注释行g2[1].comments = (string[])annotates.Clone();并立即尝试代码。反序列化时您将面临错误。我怎么能避免呢?我应该将包含数组的结构定义为一个类并将它们全部新建(希望我正在寻找基于结构的类型的解决方案)?

修改 我将结构更改为类,并通过新建每个实例它工作正常。这是代码:

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

namespace Serialization
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] annotates = { "1", "2"};
            GuidesClass[] g1 = new GuidesClass[2];
            g1[0] = new GuidesClass();
            g1[0].comments = (string[])annotates.Clone();
            g1[1] = new GuidesClass();
            g1[1].comments = (string[])annotates.Clone();

            GuidesClass[] g2 = new GuidesClass[2];
            g2[0] = new GuidesClass();
            g2[0].comments = (string[])annotates.Clone();
            g2[1] = new GuidesClass();
            //g2[1].comments = (string[])annotates.Clone();

            array_cls  arrStr1 = new array_cls();
            arrStr1.guides_array = g1;

            array_cls arrStr2 = new array_cls();
            arrStr2.guides_array = g2;

            using (MoveSaver objSaver = new MoveSaver(@"C:\1.bin"))
            {
                M_T mv1 = new M_T();
                M_T mv2 = new M_T();
                mv1.MoveStruc = "1";
                mv1.timeHLd = DateTime.Now;
                mv1.arr = arrStr1;
                objSaver.SaveToFile(mv1);
                mv2.MoveStruc = "2";
                mv2.timeHLd = DateTime.Now;
                mv2.arr = arrStr2;
                objSaver.SaveToFile(mv2);
            }

            using (MoveSaver svrObj = new MoveSaver())
            {
                List<M_T> MVTobjs = svrObj.DeSerializeObject(@"C:\1.bin");
                foreach (M_T item in MVTobjs)
                {
                    Console.WriteLine(item.arr.guides_array[0].comments[0]);
                }
            }
        }

    }


    public class MoveSaver : IDisposable
    {
        public void Dispose()
        {
            if (fs != null)
            {
                fs.Close();
            }
        }
        FileStream fs;
        StreamWriter sw;
        public string filename { get; set; }
        public MoveSaver(string FileName)
        {
            this.filename = FileName;
            fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        }

        public MoveSaver()
        {

        }

        ~MoveSaver()
        {
            if (fs != null)
            {
                fs.Close();
            }

        }

        public List<M_T> DeSerializeObject(string filename)
        {
            List<M_T> retList = new List<M_T>();
            M_T objectToSerialize;
            Stream stream = File.Open(filename, FileMode.Open);
            BinaryFormatter bFormatter = new BinaryFormatter();
            while (stream.Position != stream.Length)
            {
                objectToSerialize = (M_T)bFormatter.Deserialize(stream);
                retList.Add(objectToSerialize);
            }
            stream.Close();
            return retList;
        }


        public bool SaveToFile(M_T moveTime)
        {
            try
            {
                BinaryFormatter bformatter = new BinaryFormatter();
                bformatter.Serialize(fs, moveTime);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }


    [Serializable]
    public class M_T
    {
        public string MoveStruc;
        public DateTime timeHLd;
        public array_cls arr;
    }

    [Serializable]
    public class array_cls
    {
        public GuidesClass[] guides_array = new GuidesClass[10];
    }

    [Serializable]
    public class GuidesClass
    {
        public string[] comments;
        public string name;
    }
}

1 个答案:

答案 0 :(得分:1)

我玩过代码,我可以同时修改struct和class;最后我怀疑这里的问题是BinaryFormatter并不是设计成可以附加的,即我怀疑它是错误解释 next 对象中的数据作为当前的一部分。

FWIW,那些真的不应该是结构,而你(IMO)可能会过度设计保存/加载代码。我更改了它,以便save方法采用List<MoveAndTime>,并且加载代码返回 List<MoveAndTime>(即流中只有一个最外面的对象)并且它工作得很好,支持我的理论。

如果你需要能够逐渐追加单个物体,我建议使用protobuf-net;您可以使用SerializeWithLengthPrefix以适合追加的方式编写对象,DeserializeWithLengthPrefix从流中读取单个对象,或DeserializeItems读取({1}}作为序列)流中的所有项目。


例如,使用protobuf-net v2(目前仅作为代码提供):

using System;
using System.Collections.Generic;
using System.IO;
using ProtoBuf;


namespace Serialization
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] annotates = { "1", "2" };
            Guides[] g1 = new Guides[2];
            g1[0].comments = (string[])annotates.Clone();
            g1[1].comments = (string[])annotates.Clone();

            Guides[] g2 = new Guides[2];
            g2[0].comments = (string[])annotates.Clone();
            g2[1].comments = (string[])annotates.Clone();//to be commented later

            arrayStruct arrStr1 = new arrayStruct();
            arrStr1.guides_array = g1;

            arrayStruct arrStr2 = new arrayStruct();
            arrStr2.guides_array = g2;

            using (Stream file = File.Create(@"1.bin"))
            {
                MoveAndTime mv1 = new MoveAndTime();
                MoveAndTime mv2 = new MoveAndTime();
                mv1.MoveStruc = "1";
                mv1.timeHLd = DateTime.Now;
                mv1.arr = arrStr1;
                Serializer.SerializeWithLengthPrefix(file, mv1, PrefixStyle.Base128, Serializer.ListItemTag);
                mv2.MoveStruc = "2";
                mv2.timeHLd = DateTime.Now;
                mv2.arr = arrStr2;
                Serializer.SerializeWithLengthPrefix(file, mv2, PrefixStyle.Base128, Serializer.ListItemTag);
            }

            using (Stream file = File.OpenRead(@"1.bin"))
            {
                List<MoveAndTime> MVTobjs = Serializer.Deserialize<List<MoveAndTime>>(file);
                foreach (MoveAndTime item in MVTobjs)
                {
                    Console.WriteLine(item.arr.guides_array[0].comments[0]);
                }
            }
        }

    }

    [ProtoContract]
    public struct MoveAndTime
    {
        [ProtoMember(1)]
        public string MoveStruc;
        [ProtoMember(2)]
        public DateTime timeHLd;
        [ProtoMember(3)]
        public arrayStruct arr;
    }

    [ProtoContract]
    public struct arrayStruct
    {
        [ProtoMember(1)]
        public Guides[] guides_array;
    }

    [ProtoContract]
    public struct Guides
    {
        [ProtoMember(1)]
        public string[] comments;
        [ProtoMember(2)]
        public string name;
    }
}

v1(可用作dll;更稳定)几乎相同,但不支持结构 - 只有类。

但要强调:

  • 他们应该是班级
  • 公共领域是个坏主意