忽略 YamlDotNet 中基类的成员

Pum*_*per 1 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 6

您可以重写派生类中的属性并在那里应用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;
  }
}
Run Code Online (Sandbox Code Playgroud)