我被困在這個問題,我一直在尋找答案的任何地方,但沒有找到適合我的問題的東西。我想序列化對象並將其保存到二進制文件中,並將其作爲列表,因爲它將返回多行記錄。序列化對象然後反序列化爲列表<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條記錄,所以 –