如何使用二进制反序列化从文件文本文件中反序列化 [英] How to Deserialize using binary Deserialization from file text file

查看:53
本文介绍了如何使用二进制反序列化从文件文本文件中反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static List<Restaurant> LoadRestaurantList() 
{
    FileStream fs = new FileStream("Restaurant.txt", FileMode.OpenOrCreate); 
    BinaryFormatter bf = new BinaryFormatter(); 
    List<Restaurant> rest =(List<Restaurant>)bf.Deserialize(fs); 
    fs.Close(); 
    return rest; 
}

我已将我拥有的通用列表序列化到Restaurant.txt"文件中.

I have Serailze the generic list which I have, into "Restaurant.txt" file.

现在我想反序列化它并将其返回到通用列表中,我已经尝试过但它不工作,并给出错误无效的转换表达式".

now I want to Deserialize the same and return it into a Generic List, I have tried but its not working and it is giving error "Invalid Cast Expression".

这是序列化代码:

public static void SaveRestaurantList(List<Restaurant> 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(); 
}

谁能帮忙解决这个问题.

Can anyone please help in solving out this.

推荐答案

序列化和反序列化是对立的.这意味着序列化期间使用的类型在反序列化期间需要相同.

Serialization and Deserialization are each others opposites. This means the type(s) used during serialization needs to be the same during deserialization.

在您的代码中,情况并非如此.您序列化 Restaurant 类型,但是当您反序列化时,您需要一个 List.

In your code that is not the case. You serialize Restaurant types but when you deserialize you expect a List.

按如下方式调整您的序列化代码:

Adapt your serialization code as follows:

public static void SaveRestaurantList(List<Restaurant> restaurantList) 
{ 
   using(FileStream fs = new FileStream("Restaurant.txt", FileMode.Create, FileAccess.Write))
   {
       BinaryFormatter bf = new BinaryFormatter(); 
       bf.Serialize(fs, restaurantList); 
   }
}

这篇关于如何使用二进制反序列化从文件文本文件中反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆