【发布时间】:2011-03-05 08:56:18
【问题描述】:
我提供了一个最少的代码来模拟这个场景。代码如下:
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;
}
}
在这段代码中,一个结构包含多个结构,其中一个包含一个数组。试一下代码,它编译得很好,但在实际场景中,整个数组没有被填充,所以会有其他数组元素未指定。要查看此效果(实际效果!)注释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;
}
}
【问题讨论】:
-
出于好奇,为什么它们是结构体?它们看起来不像典型的结构(特别是因为它们是可变的),并且没有充分的理由默认它们应该是类。
-
@Oded:“输入流不是有效的二进制格式”,在实际代码中,错误与二进制标头有关。尝试编译带有注释行的代码,您将看到错误。
-
@Marc:我需要一个地方来保存基于用户交互的一些变量,并且我没有为它们实现任何方法。我的所有结构都不需要初始化它们的变量。我认为它是 class 还是 struct 对我来说没有什么不同,但在我看来 struct 就足够了。如果我必须这样做,或者我将在运行时遇到有关此类数组初始化和锯齿状数组的严重问题,请现在告诉我:D
-
@Yasser - struct vs class 的选择有nothing,重复:nothing与是否想要有关初始化或方法。那些不是价值类型;它们不应该是结构。我还没有弄清楚这个奇怪(但经常重复)的概念来自哪里......
-
但是要澄清一下;类也会出现同样的错误; IMO,这里的问题是 BinaryFormatter 不是可附加的。
标签: c# serialization deserialization