从ObservableObject继承的序列化模型

问题描述 投票:0回答:1

我想序列化和反序列化从MvvmLight.ObservableObject继承的模型对象。尝试使用System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject反序列化对象会抛出System.Runtime.Serialization.InvalidDataContractException,并带有基本类(即MvvmLight.ObservableObject)没有DataContractAttributeSerializableAttribute的信息。我的无效模型如下所示:

using GalaSoft.MvvmLight;

[DataContract]
public class MyModel : ObservableObject
{
  [IgnoreDataMember]
  private int _id;
  [DataMember]
  public int Id
  {
      get => _id;
      set => Set(ref _id, value);
  }
}

删除[DataContract]之后,没有例外,但是也没有反序列化的数据。

解决方案可能是创建具有相同属性但不继承自ObservableObject的MyModel副本MyModelSerializable,并将其用于序列化。反序列化后,可以使用MyModel对象的数据创建MyModelSerializable对象。有更好的解决方案吗?

编辑:根据要求链接到GalaSoft.MvvmLight.ObservableObject的代码:https://github.com/lbugnion/mvvmlight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(PCL)/ObservableObject.cs

c# serialization mvvm-light
1个回答
0
投票

如果无法使用DataContract标记ObservableObject,则不能在此处使用DataContract属性。所以在您的情况下,我认为您无法标记ObservableObject。

© www.soinside.com 2019 - 2024. All rights reserved.