I am trying to Deserialize an object of type ListManager, but get a cast-error when trying. Im not sure what im doing wrong.
I serialize the object just fine by sending in
b.Serialize(fileStream, obj);
But when trying to deserialize the file back to an instance of a Listmanager I get cast error. The class is called "AnimalManager", and inherits from ListManager. This class contains a list of objects of type Animal. How come it wants to cast to animal, instead of Listmanager?
Object of type "AnimalManager" cannot be converted to object of type "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>
{
}
Calling from Form1:
private void button4_Click(object sender, EventArgs e)
{
var filepath = "test.bin";
if (manager.BinaryDeSerialize(filepath))
{
MessageBox.Show("hhohjo");
}
}
Going to ListManager Instance(AnimalManager)
public bool BinaryDeSerialize(string fileName)
{
var test = BinSerializerUtility.OpenBin<T>(fileName);
return true;
}