如何使用文件文本文件中的二进制反序列化反序列化
public static List LoadRestaurantList() { FileStream fs = new FileStream("Restaurant.txt", FileMode.OpenOrCreate); BinaryFormatter bf = new BinaryFormatter(); List rest =(List)bf.Deserialize(fs); fs.Close(); return rest; }
我将Serailze的通用列表变成了“Restaurant.txt”文件。
现在我想反序列化相同并将其返回到通用列表,我已经尝试但它不工作,它给出错误“无效的演员表达”。
这是序列化代码:
public static void SaveRestaurantList(List restaurantList) { FileStream fs = new FileStream("Restaurant.txt", FileMode.Create, FileAccess.Write); BinaryFormatter bf = new BinaryFormatter(); for (int i = 0; i < restaurantList.Count; i++) { Restaurant r = new Restaurant(); r = (Restaurant)restaurantList[i]; bf.Serialize(fs, r); fs.Flush(); } fs.Close(); }
任何人都可以帮助解决这个问题。
序列化和反序列化是彼此相反的。 这意味着序列化期间使用的类型在反序列化期间需要相同。
在你的代码中并非如此。 您序列化餐厅类型,但是当您反序列化时,您期望一个列表。
调整序列化代码如下:
上述就是C#学习教程:如何使用文件文本文件中的二进制反序列化反序列化分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public static void SaveRestaurantList(List restaurantList) { using(FileStream fs = new FileStream("Restaurant.txt", FileMode.Create, FileAccess.Write)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, restaurantList); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1012634.html