c# - .NET 中的序列化

标签 c# .net binary-serialization

我的任务是序列化和反序列化一个对象。

我想知道:

  • 我的对象是否按照我正在执行的方式序列化
  • 我如何知道我的对象正在序列化或反序列化

我不是在序列化方法中传递对象,而是传递object.properties。这会以任何方式影响它吗?

FileStream fs = new FileStream(@"D:\Rough Work\Serialization\Serialization\bin\Debug\Log.txt",FileMode.OpenOrCreate);
Laptop obj = new Laptop();
obj.Model = 2;
obj.SerialNumber = 4;
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, obj.Model);
formatter.Serialize(fs, obj.SerialNumber);

[Serializable]
class Laptop
{
    public int Model;
    public int SerialNumber;
}

最佳答案

  • 如果您可以成功反序列化一个对象,那么您就正确地序列化了它。
  • 您不需要单独序列化属性。您可以序列化整个对象并以相同的方式反序列化它。

    using (var fs = new FileStream(@"D:\Rough Work\Serialization\Serialization\bin\Debug\Log.txt",FileMode.OpenOrCreate))
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(fs, obj);
    }
    
    using (var fs = new FileStream(@"D:\Rough Work\Serialization\Serialization\bin\Debug\Log.txt",FileMode.OpenOrCreate))
    {
        var formatter = new BinaryFormatter();
        obj = formatter.Deserialize(fs) as Laptop;
    }
    

如果您的问题是笔记本电脑类如何知道它正在被序列化,那么您可能需要实现 ISerializable界面。

参见BinaryFormatter.Deserialize

关于c# - .NET 中的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8225428/

相关文章:

c# - 如何避免 .NET CF 3.5 和 CE 6 R3 中的严重错误

.net - C# 类库不会注册 COM

java - HashMap<String,Double> 的格式错误的二进制序列化

c# - 反序列化一个没有类型的对象

c# - 如何填充 OpenFileDialog.ShowDialog 方法

c# - SharpZipLib 的基础知识。我错过了什么?

c# - 从基类继承

c# - 如何在 OxyPlot 图表上绘制多个 LineSeries?

.net - 升级 .NET 应用程序数据层

c# - 如何序列化字体