不要序列化 ​​Caliburn.Micro IsNotifying 属性

Don't serialize Caliburn.Micro IsNotifying property

我正在我的 ModelBase class 中实现 INotifyPropertyChanged,这样我所有派生的 classes 都可以访问 INotifyPropertyChanged 方法和事件。

我在我的项目中使用 Caliburn.Micro,所以我通过在我的 IModelBase 接口中实现 INotifyPropertyChangedEx 然后在我的 ModelBase class.

中扩展 PropertyChangedBase 来做到这一点

除了 PropertyChangedBase 中的 IsNotifying 属性 正在使用我的模型进行序列化外,这一切都很好。我尝试了一些方法,但无法让它停止序列化。

我尝试覆盖 ModelBase 中的 IsNotifying 并将 [XmlIgnore] 添加到 属性。我还尝试通过在我的 ModelBase class 中使用 new 关键字来隐藏 IsNotifying。这些都不起作用。

我从 github 复制了 PropertyChangedBase 代码,将其放入我自己的 PropertyChangedBase class,然后将 [XmlIgnore] 添加到 IsNotifying 属性。这有效,但并不理想。

有什么想法吗?这可以做到吗?我应该只使用 Caliburn.Micro PropertyChangedBase 并实现我自己的吗?实现 INotifyPropertyChanged 并不困难。我只是想使用 Caliburn.Micro 中的那个,因为我已经在使用该库了。

这是一个将 XML 写入控制台的简单示例

using System;
using System.IO;
using System.Xml.Serialization;
using Caliburn.Micro;

namespace CaliburnPropertyChangedBase
{
    internal class Program
    {
        private static void Main()
        {
            var myModel = new MyModel {SomeProperty = "Test"};

            Console.WriteLine(myModel.SerializeObject());
            Console.ReadKey();
        }
    }

    public static class XmlHelper
    {
        public static string SerializeObject<T>(this T toSerialize)
        {
            var xmlSerializer = new XmlSerializer(toSerialize.GetType());

            using (var textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, toSerialize);
                return textWriter.ToString();
            }
        }
    }

    public interface IModelBase : INotifyPropertyChangedEx
    {
    }

    public class ModelBase : PropertyChangedBase, IModelBase
    {
    }

    public interface IMyModel : IModelBase
    {
        string SomeProperty { get; set; }
    }

    public class MyModel : ModelBase, IMyModel
    {
        public string SomeProperty { get; set; }
    }
}

这是输出

<?xml version="1.0" encoding="utf-16"?>
<MyModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <IsNotifying>true</IsNotifying>
  <SomeProperty>Test</SomeProperty>
</MyModel>

在您的 SerializeObject<T> 方法中,试试这个:

var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(PropertyChangedBase), "IsNotifying", new XmlAttributes
{
    XmlIgnore = true,
});
var xmlSerializer = new XmlSerializer(toSerialize.GetType(), overrides);

XmlAttributeOverrides 类型允许您自定义使用 xml 序列化程序属性可以完成的所有事情 - 但在运行时 。当我发现时,我很惊讶。

进一步阅读:.NET Framework Documentation