【发布时间】: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