1

我有一个类,我想用 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 的元素有没有办法在不改变基类的情况下从序列化中排除这个元素?

4

2 回答 2

4

您可以覆盖派生类中的属性并在那里应用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;
  }
}
于 2015-05-20T10:58:34.030 回答
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();
    
于 2018-04-06T14:46:14.993 回答