在我的班级“DiaryManager”中,我得到了两个具有两种不同类型(T)的列表,我想将它保存到文件中,然后我想加载它。正如我将向您展示的那样,我让它与我的列表之一一起使用。
我在工作代码中保存和加载的列表名为“m_diary”。保存方法是这样的:
/// <summary>
/// Saves the object information
/// </summary>
public void Save()
{
// Gain code access to the file that we are going
// to write to
try
{
// Create a FileStream that will write data to file.
FileStream writerFileStream =
new FileStream(DATA_FILENAME, FileMode.Create, FileAccess.Write);
// Save our dictionary of friends to file
m_formatter.Serialize(writerFileStream, m_diary);
// Close the writerFileStream when we are done.
writerFileStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我的加载方法是这样的:
/// <summary>
/// Load the object to the program
/// </summary>
public void Load()
{
// Check if we had previously Save information of our friends
// previously
if (File.Exists(DATA_FILENAME))
{
try
{
// Create a FileStream will gain read access to the
// data file.
FileStream readerFileStream = new FileStream(DATA_FILENAME,
FileMode.Open, FileAccess.Read);
// Reconstruct information of our friends from file.
m_diary = (List<Diary>)
m_formatter.Deserialize(readerFileStream);
// Close the readerFileStream when we are done
readerFileStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
“DATA_FILENAME”是这个常量:
private const string DATA_FILENAME = "TrainingDiary.dat";
此代码在我的 Windows 窗体类中完美运行。但现在 Iv 添加了一个不同类型的列表。
如何保存第二个列表并将其加载到?:)
最好的问候 Cyrix