如何反序列化当前类?解决LoadClass中this只读赋值错误
解决思路:类的序列化加载问题
你遇到的报错是因为C#中this是只读引用,无法直接赋值替换整个实例。以下是两种实用的解决方案:
方案1:用静态方法返回新实例
这是最简洁且符合常规写法的方案,将加载逻辑改为静态方法,直接返回反序列化后的新对象:
[Serializable] public class Test { // 示例属性 public string Name { get; set; } public int Age { get; set; } public void SaveClass(string filePath) { // 使用using自动释放流资源,比手动Close更安全 using (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); } } // 改为静态方法,返回新的Test实例 public static Test LoadClass(string filePath) { using (Stream stream = System.IO.File.OpenRead(filePath)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); return (Test)binaryFormatter.Deserialize(stream); } } }
使用示例:
// 保存实例 Test myTest = new Test { Name = "示例名称", Age = 30 }; myTest.SaveClass("test_data.bin"); // 加载新实例 Test loadedTest = Test.LoadClass("test_data.bin");
方案2:实例方法覆盖当前对象属性
如果必须在现有实例上加载数据(比如该实例已和其他对象存在引用关联),可以先反序列化出临时对象,再手动复制所有属性/字段到当前实例:
[Serializable] public class Test { public string Name { get; set; } public int Age { get; set; } public void SaveClass(string filePath) { using (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); } } public void LoadClass(string filePath) { using (Stream stream = System.IO.File.OpenRead(filePath)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); Test tempInstance = (Test)binaryFormatter.Deserialize(stream); // 逐一复制所有属性到当前实例 this.Name = tempInstance.Name; this.Age = tempInstance.Age; // 若有其他属性、私有字段,需同步添加复制逻辑 } } }
注意:这种方式的缺点是类结构变更时,需要同步更新属性复制逻辑;如果涉及私有字段,可能需要用反射批量复制,会增加代码复杂度。
另外补充:BinaryFormatter在.NET Core 3.0+及.NET 5+版本中已被标记为过时,存在安全风险,新项目建议改用System.Text.Json、Newtonsoft.Json等更安全的序列化方案。
内容的提问来源于stack exchange,提问作者Jonathan Barraone
相关产品推荐
相关产品推荐

