我已经阅读了很多代码,但没有一个能解决问题。首先是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Serialization
{
class Program
{
static void Main(string[] args)
{
using (MoveSaver objSaver = new MoveSaver(@"C:\1.bin"))
{
MoveAndTime mv1, mv2;
mv1.MoveStruc = "1";
mv1.timeHLd = DateTime.Now;
objSaver.SaveToFile(mv1);
mv2.MoveStruc = "2";
mv2.timeHLd = DateTime.Now;
objSaver.SaveToFile(mv2);
}
using (MoveSaver svrObj = new MoveSaver())
{
MoveAndTime[] MVTobjs = svrObj.DeSerializeObject(@"C:\1.bin");
foreach (MoveAndTime item in MVTobjs)
{
//Do Something
}
}
}
}
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 MoveAndTime[] DeSerializeObject(string filename)
{
MoveAndTime[] objectToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
objectToSerialize = (MoveAndTime[])bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
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;
}
}
代码模仿了在程序中保存用户的所有操作的需要。稍后会在该程序上显示(比如你打牌等等,你想要复习:D发生了什么)。问题是当调用DeSerializeObject函数时,行objectToSerialize = (MoveAndTime[])bFormatter.Deserialize(stream);
抛出异常(肯定在运行时),从单个对象到数组的强制转换无效:
无法投射类型的对象 输入'Serialization.MoveAndTime' 'Serialization.MoveAndTime []'。
有什么想法吗?任何改进或完全改变的方法都是值得赞赏的。
答案 0 :(得分:1)
您正在将单个MoveAndTime
实例保存到该文件中,但是您正在尝试读取它们的数组。
答案 1 :(得分:1)
请像这样修改您的主要区块。我认为它可以达到你想要的效果。
static void Main(string[] args)
{
using (MoveSaver objSaver = new MoveSaver(@"C:\1.bin"))
{
MoveAndTime[] MVobjects = new MoveAndTime[2];
MoveAndTime mv1, mv2;
mv2 = new MoveAndTime();
mv1 = new MoveAndTime();
mv1.MoveStruc = "1";
mv1.timeHLd = DateTime.Now;
mv2.MoveStruc = "2";
mv2.timeHLd = DateTime.Now;
MVobjects[0] = new MoveAndTime();
MVobjects[0] = mv1;
MVobjects[1] = new MoveAndTime();
MVobjects[1] = mv2;
objSaver.SaveToFile(MVobjects);
}
using (MoveSaver svrObj = new MoveSaver())
{
MoveAndTime[] MVTobjs = svrObj.DeSerializeObject(@"C:\1.bin");
foreach (MoveAndTime item in MVTobjs)
{
//Do Something
Console.WriteLine(item.MoveStruc);
Console.WriteLine(item.timeHLd);
}
}
}
由于