我被困在这个问题,我一直在寻找答案的任何地方,但没有找到适合我的问题的东西。我想序列化对象并将其保存到二进制文件中,并将其作为列表,因为它将返回多行记录。序列化对象然后反序列化为列表<object> C#
所以,这是我的课
[Serializable]
public class DTOMultiConfig
{
public string Key { get; set; }
public string KeyValue { get; set; }
}
[Serializable]
public class DTOMultiConfigs : List<DTOMultiConfig>
{
public void Dispose()
{
}
}
,我用这些方法我在网上找到。这是我如何序列化我的对象,这部分工作
public void Editor_Config(DTOMultiConfig dto)
{
if (dto.ID == 0)//new
{
dto.ID = 0;
WriteToBinaryFile(BinPath, dto, true);
}
else//edit
{
}
}
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = System.IO.File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
这是我如何使用deserialize
方法,我不知道,我敢肯定,我做了错误的方式,因为它不工作所有。 ReadFromBinaryFile
在“返回”声明之前停止工作。
public PartialViewResult ShowListOfConfigs()
{
List<DTOMultiConfig> dto = new List<DTOMultiConfig>();
//DESERIALIZE
dto = ReadFromBinaryFile<List<DTOMultiConfig>>(BinPath);
return PartialView("_ListOfConfigs", dto);
}
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = System.IO.File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
任何答案与一些解释将不胜感激。
你得到的例外是什么?我怀疑你的问题是你写了一个DTOMultiConfig实例,但是试图读取一个List,因为你的类型的单个实例的二进制表示与列表的二进制表示不同,所以它不能工作。 –
dnickless
你好,谢谢你的回应,我得到了这个exeption {“无法将类型为'MVCHowTo.Models.DTOMultiConfig'的对象转换为类型'System.Collections.Generic.List'1 [MVCHowTo.Models.DTOMultiConfig]'。 “} –
因此,在写入二进制文件时,是否应该让我的dtoMultiConfig成为一个列表?因为我一次只写1条记录,所以 –