【发布时间】:2017-03-05 12:45:54
【问题描述】:
我正在尝试反序列化 ListManager 类型的对象,但尝试时出现转换错误。我不确定我做错了什么。
我通过发送来序列化对象就好了
b.Serialize(fileStream, obj);
但是当试图将文件反序列化回 Listmanager 的实例时,我得到了转换错误。该类名为“AnimalManager”,继承自 ListManager。此类包含 Animal 类型的对象列表。怎么想投给animal,而不是Listmanager?
“AnimalManager”类型的对象无法转换为“Animal”类型的对象。
public static T OpenBin<T>(string filePath)
{
FileStream fileStream = null;
object obj;
try
{
if (!File.Exists(filePath)) throw new FileNotFoundException("The file" + " was not found. ", filePath);
fileStream = new FileStream(filePath, FileMode.Open);
var b = new BinaryFormatter();
obj = b.Deserialize(fileStream);
}
finally
{
fileStream?.Close();
}
return (T)obj;
}
[Serializable]
public class ListManager<T> : IListManager<T>
{
private List<T> _mList;
public ListManager()
{
_mList = new List<T>();
}
}
[Serializable]
public class AnimalManager : ListManager<Animal>
{
}
从 Form1 调用:
private void button4_Click(object sender, EventArgs e)
{
var filepath = "test.bin";
if (manager.BinaryDeSerialize(filepath))
{
MessageBox.Show("hhohjo");
}
}
转到 ListManager 实例(AnimalManager)
public bool BinaryDeSerialize(string fileName)
{
var test = BinSerializerUtility.OpenBin<T>(fileName);
return true;
}
【问题讨论】:
-
你能展示你对OpenBin的调用以及你的序列化吗?
-
请阅读How to Ask 并提供minimal reproducible example。您没有反序列化为与以前序列化相同的类型,或者您在某处弄乱了
Ts,但我们无法从显示的代码中分析这一点。
标签: c# generics serialization