1

I have a class which I want to serialize with 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);
        }
    }
}

My problem is, in the base class is an element named: IsNotifying Is there a way to exclude this element from serialization, without the change of the base class?

Pang
  • 9,564
  • 146
  • 81
  • 122
Pumper
  • 233
  • 1
  • 6
  • 11

2 Answers2

5

You could override the property in the derived class and apply the YamlIgnore attribute there. While the sample below works, I suspect for more complicated class hierarchies you would really need to ensure no behavior changes.

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;
  }
}
BgRva
  • 1,521
  • 12
  • 26
1

I had a similar problem (needed to filter properties of a particular type from classes I couldn't change, so using the attribute was not an option) and is what I came up with:

  1. Create a custom type inspector:

     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. Create the serializer as follows:

     var builder = new SerializerBuilder();
     builder.WithTypeInspector(inspector => new MyTypeInspector(inspector));
     var serializer = builder.Build();
    
Pang
  • 9,564
  • 146
  • 81
  • 122
Pawel Gorczynski
  • 1,227
  • 1
  • 15
  • 17
  • I used this with removing properties from the 'props' that are overridden in the descendent class – Andras Apr 13 '22 at 15:40