【问题标题】:How to Deserialize the current class如何反序列化当前类
【发布时间】:2022-11-23 03:01:08
【问题描述】:

我不知道这是否可能,但假设我有一个课程:

    [Serializable]
    public class Test
    {
        //Properties and functions would go here.

        public void SaveClass(string FilePath)
        {
            System.IO.Stream stream = System.IO.File.Create(FilePath);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            binaryFormatter.Serialize(stream, this);
            stream.Close();
        }

        public void LoadClass(string FilePath)
        {
            System.IO.Stream stream = System.IO.File.OpenRead(FilePath);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            this = binaryFormatter.Deserialize(stream); //It returns an error saying that 'this' is readonly. 
            stream.Close();
        }
    }

现在我希望能够保存和加载课程。 SaveClass 工作正常,但 LoadClass 返回错误,因为我无法将任何内容分配给 this。有没有办法可以从文件中加载类,或者这是不可能的。

【问题讨论】:

  • 作为更好的设计 - 将序列化逻辑与数据分开
  • LoadClass 应该是一个静态方法,返回反序列化的 Test 实例。 public static Test LoadClass(string FilePath) { //deserialize, cast and return }。

标签: c# serialization deserialization


【解决方案1】:

将LoadClass设为静态,类似于:

 public static Test LoadClass(string FilePath)
 {
     System.IO.Stream stream = System.IO.File.OpenRead(FilePath);
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     var newTest = binaryFormatter.Deserialize(stream);
     stream.Close();
     return newTest;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    相关资源
    最近更新 更多