XmlSerializer 的新行为(使用新的 XmlAttributes?)

New behaviours (with new XmlAttributes?) for XmlSerializer

是否可以创建对 XmlSerializer 施加新行为的新 XmlAttributes?

例如,假设我想要一个 XmlAttrbute,它指示如果 class 的给定 field/property 的值为 null,则是否要序列化。

我知道,对于此示例,您可以使用 [Propert/Field]ShouldSerialize 或 [Property/Field]Specified 甚至 XmlAttributeOverrides,但这种方法可能意味着大量工作。

使用反编译器软件,我转到 System.Xml.Serialization dll 并打开 classes,如 XmlIgnoreAttribute 或 XmlElementAttribute。

在 XmlElementAttribute 中我发现了以下内容

public bool IsNullable {
    get { return nullable; }
    set { 
        nullable = value; 
        nullableSpecified = true;
    }
}

但不幸的是,内部的 nullableSpecified 属性 :( 我看不出它是否具有相同的效果 [Propert/Field]ShouldSerialize 或 [Property/Field]Specified。

不,您不能修改 XmlSerializer 的工作方式。

在你的情况下,一个可行的解决方法是使用一些额外的工具,这些工具会在构建时根据你的自定义属性更改你的代码(添加那些讨厌的 [Propert/Field]ShouldSerialize 成员) - 例如Post Sharp(据我所知,免费版本足以满足您的需求)。