【问题标题】:Serialization exception using C#使用 C# 的序列化异常
【发布时间】:2015-06-02 22:55:33
【问题描述】:

我是C# 的新手,正在尝试将一些信息写入文件。当我在同一个 .cs 文件中有 Car 类时,程序可以正常运行,但是当我将这个类删除到项目中的另一个 .cs 文件中时,我得到了运行时错误

“SerializationException 未处理:ObjectManager 发现了无效数量的修复。这通常表明格式化程序中存在问题”。

下面是包含 Car 类的代码。当我将类移动到它自己的 Car.cs 文件时,开始抛出错误。

namespace ConsoleApplication2
{
  class Program
  {

     [Serializable()]
     public class Car
     {
         public string Make { get; set; }
         public string Model { get; set; }
         public int Year { get; set; }

         public Car(string make, string model, int year)
        {
             Make = make;
             Model = model;
             Year = year;
        }
     }
    /// <summary>
    /// Deserializes list of cars and returns the list to user
    /// </summary>
    /// <returns>Returns deserialized car list</returns>
    public List<Car> ReadList()
    {
        //create local list to hold data
        List<Car> carList = new List<Car>();

        try
        {
            using (Stream stream = File.Open("data.bin", FileMode.Open))
            {
                BinaryFormatter bin = new BinaryFormatter();

                //point carList to deserialized stream
                carList = (List<Car>)bin.Deserialize(stream);

            }
        }
        catch (IOException)
        {
        }

        return carList;
     }

【问题讨论】:

标签: c# serialization deserialization


【解决方案1】:

首次创建 data.bin 时,类类型与数据一起存储。如果更改类的命名空间,则格式化程序将无法找到存储的类。

【讨论】:

  • 有趣,我删除了data.bin并重新运行程序,它运行良好,感谢您的帮助
【解决方案2】:

如果您使用 Asp.Net 并且遇到此问题,您需要清除浏览器缓存和 cookie,因为使用干净 bin 文件夹的解决方案不起作用(重新启动 iis 也不起作用)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    相关资源
    最近更新 更多