忽略YamlDotNet中基类的成员

时间:2015-04-09 09:46:05

标签: yamldotnet

我有一个我想用YamlDotNet序列化的类:

public class AwesomeClass : PropertyChangedBase
{
    private bool _element1;
    private bool _enabled;

    public bool Element1
    {
        get { return _element1; }
        set
        {
            _element1 = value;
            NotifyOfPropertyChange(() => Element1);
        }
    }

    public bool Enabled
    {
        get { return _enabled; }
        set
        {
            _enabled = value;
            NotifyOfPropertyChange(() => Enabled);
        }
    }
}

我的问题是,在基类中有一个名为IsNotifying的元素 有没有办法在不更改基类的情况下从序列化中排除这个元素?

2 个答案:

答案 0 :(得分:1)

您可以覆盖派生类中的属性并在其中应用YamlIgnore属性。虽然下面的示例有效,但我怀疑您确实需要更复杂的类层次结构来确保没有行为更改。

public class AwesomeClass : PropertyChangedBase
{
  [YamlIgnore]
  public new bool IsNotifying
  {
    get { return base.IsNotifying; }
    set { base.IsNotifying = value; }
  }

  [YamlIgnore]
  public override bool Blah
  {
    get { return base.Blah; }
    set { base.Blah = value; }
  }
}

public class PropertyChangedBase
{
  public bool IsNotifying
  {
    get;
    set;
  }

  public virtual bool Blah
  {
    get; 
    set;
  }
}

答案 1 :(得分:0)

我遇到了类似的问题(需要从我无法更改的类中过滤特定类型的属性,因此使用该属性不是一个选项)并且是我想出的:

  1. 创建自定义类型检查器:

    public class MyTypeInspector : TypeInspectorSkeleton
    {
        private readonly ITypeInspector _innerTypeDescriptor;
    
        public MyTypeInspector(ITypeInspector innerTypeDescriptor)
        {
            _innerTypeDescriptor = innerTypeDescriptor;
        }
    
        public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container)
        {
            var props = _innerTypeDescriptor.GetProperties(type, container);
            props = props.Where(p => !(p.Type == typeof(Dictionary<string, object>) && p.Name == "extensions"));
            props = props.Where(p => p.Name != "operation-id");
            return props;
        }
    }
    
  2. 按如下方式创建序列化程序:

            var builder = new SerializerBuilder();
            builder.WithTypeInspector(inspector => new MyTypeInspector(inspector));
            var serializer = builder.Build();