好吧,我有一个类“EIR”,它是一个基于其基类“ExpenseReport”的列表,如下所示:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using System.Linq;
using System.Text;
namespace Payroll
{
[Serializable]
public class EIR : List<ExpenseItem>
{
public void WriteToFile(string filename)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream("D:\\myExpensesUpdated.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, filename);
stream.Close();
}
catch (Exception ex)
{
Console.WriteLine("Unable to serialize Expenses: {0}", ex.Message);
}
}
public static EIR ReadFromFile(string filename)
{
EIR iRost = new EIR();
try
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream("D:\\myExpensesUpdated.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
iRost = (EIR)formatter.Deserialize(stream);
}
catch (Exception ex)
{
Console.WriteLine("Unable to deserialize Expenses: {0}", ex.Message);
}
return iRost;
}
}
}
}
这个 ReadFromFile 部分是我遇到问题的地方:
在主程序中,这部分尝试调用 ReadFromFile 并显示新更新的项目,但我收到错误“无法将 'System.String' 类型的对象转换为 'Payroll.EIR' 类型”。
try
{
EIR expensesUpdated = EIR.ReadFromFile("D:\\myExpensesUpdated.bin");
foreach (var e in expensesUpdated) Console.WriteLine("Updated: {0}", e.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
如何让 iRost 转换为 Payroll.EIR 类?有没有办法将序列化的字符串转换为类?