简体   繁体   English

使用 C# 的序列化异常

[英]Serialization exception using C#

I am new toC# and am trying to write some information to a file.我是C#新手,正在尝试将一些信息写入文件。 I got the program running properly when I have the Car class in the same .cs file, but when I remove this class into another .cs file in the project, I get the runtime error of当我在同一个 .cs 文件中有 Car 类时,我让程序正常运行,但是当我将这个类删除到项目中的另一个 .cs 文件时,我得到了运行时错误

"SerializationException was unhandled: The ObjectManager found an invalid number of fixups. This usually indicates a problem in the Formatter". “SerializationException 未处理:ObjectManager 发现了无效数量的修复。这通常表明格式化程序中存在问题”。

Below is the code with the Car class included.下面是包含 Car 类的代码。 When I move the class to its own Car.cs file the error starts getting thrown.当我将类移动到它自己的 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;
     }

When the data.bin was first created the class type is stored along with the data.首次创建 data.bin 时,类类型与数据一起存储。 if you change the class's namespace, then the formatter is not able to find the class that was stored.如果更改类的命名空间,则格式化程序将无法找到存储的类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM