我如何序列化这个类

时间:2016-04-18 08:19:55

标签: c# wpf serialization

然而尝试尝试可能,我不知道如何序列化 (抱歉。我在英语词典中找到了'What the hell' 这个坏话吗?无论如何,我很抱歉)

  1. 当我使用BinaryFormatter时,它会从RelayCommand中抛出异常(我想使用XmlSerializer。我必须看到文件的文本)
    我尝试使用[XmlIgnore],但我认为似乎不适用。
  2. 当我使用XmlSerializer时,我不知道抛出异常的位置。
  3. DataContractSerializer抛出了很多异常。所以我不想用。
  4. 请帮帮我。 请理解,我不会说英语。

    这是我的班级。

    扩展解决方案。
    从主要解决方案中提到。

    [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...~~
    }
    

1 个答案:

答案 0 :(得分:0)

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

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

相关问题