在新添加的成员之后反序列化类的问题

时间:2016-02-05 22:08:35

标签: c# .net wcf serialization

我有一个简单的"可序列化的"类定义如下:

[Serializable]
public class LayoutDetails
{       
    public bool IsRefreshEnabled { get; set; }

    public string GridSettings { get; set; }

    public List<string> GroupByPropertyNames { get; set; }
}

该类已使用以下例程序列化:

using (var memoryStream = new MemoryStream())
{
   var dc = new DataContractSerializer(obj.GetType());
   dc.WriteObject(memoryStream, obj);

   memoryStream.Flush();

   memoryStream.Position = 0;
   StreamReader reader = new StreamReader(memoryStream);
   serializedObject = reader.ReadToEnd();
}

我正在尝试使用以下例程对其进行反序列化:

   var bytes = new UTF8Encoding().GetBytes(serializedObject);
   using (var stream = new MemoryStream(bytes ))
   {
      var serializer = new DataContractSerializer(type);
      var reader = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max);
      obj = serializer.ReadObject(reader, true);
   }

这很有效;但是,现在,我想向类中添加一个新属性(public int? Offset { get; set; })。当我将这个属性添加到类并尝试反序列化以前序列化的实例(没有属性)时,我得到一个例外:

Error in line 1 position 148. 'EndElement' 'LayoutDetails' from namespace 'http://schemas.datacontract.org/2004/07/WpfApplication1' is not expected. Expecting element '_x003C_Offset_x003E_k__BackingField'.

我的第一个想法是实施ISerializable并使用deserialziation ctor,所以我尝试了类似的东西,但它无法通过名字找到任何成员 - 而且我已经尝试了几种组合。 ..

public LayoutDetails(SerializationInfo info, StreamingContext context)
{
   this.IsRefreshEnabled = (bool)info.GetValue("_x003C_IsRefreshEnabled_x003E_k__BackingField", typeof(bool));
   this.IsRefreshEnabled = (bool)info.GetValue("_x003C_IsRefreshEnabled_x003E_k_", typeof(bool));
   this.IsRefreshEnabled = (bool)info.GetValue("_x003C_IsRefreshEnabled_x003E", typeof(bool));
   this.IsRefreshEnabled = (bool)info.GetValue("x003C_IsRefreshEnabled_x003E", typeof(bool));
   this.IsRefreshEnabled = (bool)info.GetValue("IsRefreshEnabled", typeof(bool));
}

使用DataContractSerializer,如何在不破坏反序列化的情况下向我的类添加新成员?#34; old&#34;实例

1 个答案:

答案 0 :(得分:4)

您可以为新属性使用支持字段,并添加属性OptionalField

[Serializable]
public class LayoutDetails
{       
    [OptionalField]
    private int? offset;

    public bool IsRefreshEnabled { get; set; }

    public string GridSettings { get; set; }

    public List<string> GroupByPropertyNames { get; set; }

    public int? Offset
    {
        get { return offset; }
        set { offset = value; }
    }
}

如果要设置默认值,可以使用属性OnDeserializing向类添加方法:

[OnDeserializing]
private void SetOffsetDefault(StreamingContext sc)
{
    offset = 123;
}