c#加载/保存对象或对象数组

本文关键字:对象 数组 保存 加载 | 更新日期: 2023-09-27 18:22:46

我认为这是我使用的代码,但如果不能加载它,就无法判断,基本上,imagebook是一个单独的对象,它存储"imagedata对象数组",其中包含用于我的加载保存的图像和整数。但是在加载子中的一条线上存在"类型"错误的问题

如果有一种方法可以保存整个imagedata数组并删除imagebook,那也没问题。

namespace FastCrack
{
    [Serializable]
    class ImageBook1
    {
        public ImageData1[] imgdat;
        public ImageBook1(ImageData1[] dat) {
            imgdat = new ImageData1[1000];
            imgdat = dat;
        }
    }
}


namespace FastCrack
{
    public partial class Form1 : Form
    {
        private void saveCrack()
        {      
        try
        {
              book1 = new ImageBook1(imagedataSheets);
            // Create a FileStream that will write data to file.
            FileStream writerFileStream = new FileStream(Filename1, FileMode.Create, FileAccess.Write); // Save our dictionary of friends to file
            this.formatter.Serialize(writerFileStream, this.book1); 
            writerFileStream.Close();
        }
        catch (Exception) {
            Console.WriteLine("Unable to save our friends' information");
        } // end try-catch
        }

        private void loadCrack()
        {
            if (File.Exists(Filename1))
            {
                try
                {
                    // Create a FileStream will gain read access to the 
                    // data file.
                    FileStream readerFileStream = new FileStream(Filename1,
                        FileMode.Open, FileAccess.Read);
                    // Reconstruct information of our friends from file.


  //this.friendsDictionary = (Dictionary<String, Friend> 
 //<--this is line from example
this.book1 = (Dictionary<ImageBook1, book1>) 
 // (Dictionary<String, Friend>)
    <--  this is the line giving me type error


                        this.formatter.Deserialize(readerFileStream);
                    // Close the readerFileStream when we are done
                    readerFileStream.Close();
                }
                catch (Exception)
                {
                    Console.WriteLine("There seems to be a file that contains " +
                        "friends information but somehow there is a problem " +
                        "with reading it.");
                } // end try-catch
            } // end if
        }
    }
}

c#加载/保存对象或对象数组

book1变量似乎是ImageBook1(不确定;您没有与我们共享其声明),因此无法为其分配字典。

序列化的任何类型也应该是反序列化的类型,因此您可能希望将其强制转换回ImageBook1:

this.book1 = (ImageBook1)this.formatter.Deserialize(readerFileStream);

如果没有,你必须编辑你的答案,并指出你想要什么类型的词典。