YamlDotNet
YamlDotNet copied to clipboard
YamlIgnoreAttribute can not apply to overrides
public abstract class CfgFileBase {
[YamlIgnore]
public virtual string Path {get;set;} = @"C:\settings.yaml";
[YamlIgnore]
public virtual xxx xxx1 {get;set;}
//...
[YamlIgnore]
public virtual xxx xxx20 {get;set;}
}
public class CfgFileForClass1 : CfgFileBase {
public override string Path {get;set;} = @"D:\c1.test\settings.yaml";
//...
}
//...
public class CfgFileForClass100 : CfgFileBase {
public override string Path {get;set;} = @"D:\c100.test\settings.yaml";
//...
}
While serializing CfgFile
to yaml, the overriden Path
was write to the output which is not desired.
Yes I can give a [YamlIgnore]
to overridden property, but what if I have 100 or more derived class and 10 or more properties per class have to attach a [YamlIgnore]
?
It's better to append a property ApplyToOverrides
to indicate this attribute should apply to overrides, like ScriptIgnore
in System.Web.Script.Serialization
:
ApplyToOverrides
of ScriptIgnore
in System.Web.Script.Serialization
I agree that this needs fixing. Is is necessary to add a property to control this behavior? Is there any use case where one would not want the YamlIgnore
to apply to an overriden property?
I think it is very rarely that one would not want the XXXIgnore
to apply to an overriden property while using a serializer library, so as you can see the ApplyToOverrides
of ScriptIgnore
is default to true
, but provided a way for user to choose not to apply it to an overriden.
This pattern can be used by YamlDotNet
as well. So, my suggestion is to add a property to control this behavior and set it's default value to allow attribute to apply to overrides.
I just verified this issue is resolved with the following code and result:
using YamlDotNet.Serialization;
var serializer = new SerializerBuilder()
.Build();
var test = new Y
{
NotIgnored = "hi",
Ignored = "bye"
};
Console.WriteLine(serializer.Serialize(test));
public class X
{
public string NotIgnored { get; set; }
[YamlIgnore]
public virtual string Ignored { get; set; }
}
public class Y : X
{
public override string Ignored { get => base.Ignored; set => base.Ignored = value; }
}
Result:
NotIgnored: hi