.NET XmlSerializer:当属性资源库具有其他代码时序列化

本文关键字:其他 代码 序列化 资源库 XmlSerializer 属性 NET | 更新日期: 2023-09-27 18:37:10

我有一个(非常缩写的)类,如下所示:

public class Widget
{
  public List<Widget> SubWidgets { get; set; }
  public Widget ParentWidget { get; set; }
  private double _ImportantValue;
  public double ImportantValue
  {
    get { return _ImportantValue; }
    set
    {
      _ImportantValue = value;
      RecalculateSubWidgets();
    }
  }
}

反序列化时,我不想重新计算子小部件。处理这种情况的最佳方法是什么?到目前为止,我唯一能想到的就是设置一个"全局"变量,说我正在反序列化并在这种情况下跳过对 RecalculateSubWidgets() 的调用,但这似乎非常笨拙。

.NET XmlSerializer:当属性资源库具有其他代码时序列化

一个简单的方法是忽略当前属性并使用另一个属性来获取反序列化值:

private double _ImportantValue;
[XmlElement("ImportantValue")]
public double ImportantValueFromXml
{
    get { return _ImportantValue; }
    set
    {
        _ImportantValue = value;
    }
}
[XmlIgnore]
public double ImportantValue
{
    get { return _ImportantValue; }
    set
    {
        _ImportantValue = value;
        RecalculateSubWidgets();
    }
}

当您反序列化时,不会调用RecalculateSubWidgets()方法,但您的私有字段仍将具有该值。当然,您可能希望稍微更改一下设计并摆脱 setter 中的函数调用以避免这种情况,但这可能是一个短期解决方案。