【问题标题】:How can I Serialize this class我怎样才能序列化这个类
【发布时间】:2016-04-18 08:19:55
【问题描述】:

但是尝试可能尝试过,我不知道如何序列化 (对不起。我在英语词典中找到了“What the hell” 这是坏话吗?无论如何我很抱歉)

  1. 当我使用 BinaryFormatter 时,它会从 RelayCommand 抛出异常(我想使用 XmlSerializer。我必须查看文件的文本)
    我尝试使用 [XmlIgnore],但我认为它似乎不适用。
  2. 我在使用XmlSerializer的时候,不知道哪里会抛出异常。
  3. DataContractSerializer 抛出很多异常。所以我不想用。

请帮助我。 请理解,我不会说英语。

这是我的课。

扩展解决方案。
参考主要解决方案。

[Serializable]
public class SerializableContextBase : INotifyPropertyChanged
{
    [field: NonSerialized()]
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }
}

主要解决方案
主要顶级类

 [Serializable]
public class ResultContext : SerializableContextBase
{
    public ResultContext() { }
 private PerformanceContextCollection _PerformanceCollection = new PerformanceContextCollection();
    public PerformanceContextCollection PerformanceCollection
    {
        get { return _PerformanceCollection; }
        set
        {
            if (_PerformanceCollection == value) { return; }
            _PerformanceCollection = value;
            RaisePropertyChanged("PerformanceCollection");
        }
    }

底层类

[Serializable]
public class PerformanceContextCollection : ObservableCollection<PerformanceContext>
{
   // some method  
   // public void Add(string Name){} ~~~
}

[Serializable]
public class PerformanceContext : SerializableContextBase
{
    [XmlIgnore]
    public RelayCommand<PerformanceContext> RemoveCommand { get; set; }
    some string, some guid...~~
}

【问题讨论】:

    标签: c# wpf serialization


    【解决方案1】:

    您的类被设计为 ViewModel,因此它们有很多与 WPF 交互相关的额外包袱。为了将信息发送到另一层,通常是人们序列化数据的原因,您通常会使用另一个类,即某种数据传输对象。我知道这听起来很迂腐,但这个解决方案也让您在序列化时不必使用相同的结构。例如,您可能希望将某些数据序列化为逗号分隔列表,而不是整个元素列表,您可能希望忽略 ViewModel 中用于轻松与 WPF 引擎交互的属性,例如使用 Visibility 属性或与布尔值 IsVisible 一起使用。

    话虽如此,如果你仍然想序列化你的类,不管怎样,最简单的方法(至少对我来说)是实现IXmlSerializable,从而自己控制序列化输出。请理解,虽然默认序列化运行良好并且通常不需要太多的开发人员工作,但它通常也会呈现极其冗长且难以阅读的 XML 输出。例如,大多数原始属性作为元素的属性看起来更好,但序列化会为每个元素创建子元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-08
      • 2022-01-11
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2019-11-10
      相关资源
      最近更新 更多