序列化没有空值

本文关键字:空值 序列化 | 更新日期: 2023-09-27 17:59:20

假设我有一个类

    [Serializable()]
public class Car
{
    public string model;
    public int year;
}

我将其序列化到名为"car.xx"的磁盘上。然后我将一个属性添加到我的car类中,这样它就会是这样的:

    [Serializable()]
public class Car
{
    public string model;
    public int year;
    public string colour;
}

然后,我将"car.xx"(包含2个字段)反序列化为包含3个字段的当前car类,这将使car类的"color"属性为null。

如何设置"新属性"不获取null值?在构造函数中设置它们不会有帮助。

我正在使用BinaryFormatter序列化程序

我希望用"

序列化没有空值

替换为null的字符串值

如果不使用XmlSerializer,则考虑使用OnDeserializedAttribute、OnSerializationAttribute、On序列化属性和OnDeserilizingAttribute属性

看看这个。

类似:

[Serializable()]
public class Car
{
    public string colour;
    public string model;
    public int year;
    [OnDeserialized()]
    internal void OnDeserializedMethod(StreamingContext context)
    {
       if (colour == null)
       {
           colour = string.Empty;
       }
    }
}

这一切都取决于序列化程序。

一些序列化程序跳过构造函数;一些序列化程序运行默认构造函数。有些让你选择。有些提供序列化回调。

因此,取决于序列化程序:

  • 编写一个公共的无参数构造函数来设置默认值(或者使用字段初始值设定项,这最终是类似的)
  • 在反序列化之前编写一个"on反序列化"序列化回调以设置默认值

或者在最坏的情况下,实现自定义序列化(ISerializable/IXmlSerializable/等,取决于序列化程序)

例如,使用BinaryFormatter:

[Serializable]
public class Car : IDeserializationCallback
{
    public string model;
    public int year;
    public string colour;
    void IDeserializationCallback.OnDeserialization(object sender)
    {
        if (colour == null) colour = "";
    }
}

对于其他序列化程序,它可能会使用[OnDeserialized]。笔记就我个人而言,即使在DTO中,我也不会公开公共领域。但是如果您使用的是BinaryFormatter,那么更改它现在是一个突破性的更改。为了完整起见,我也不会使用BinaryFormatter——它对不是非常友好。其他序列化程序也可用,对您的伤害较小。