C# 9 记录 XmlAttribute 序列化属性被忽略

C# 9 record XmlAttribute serialization attribute ignored

在这个使用 C# 记录而不是 class 的示例中,在使用标准 XmlSerializer 进行序列化时忽略 XmlAttribute 属性。这是为什么?

public record Person (
    string Name,
        
    [XmlAttribute("dte_created")]
    DateTime CreatedAt
) {
    // parameterless ctor required for xml serializer
    public Person() : this(null, DateTime.MinValue) {}
};

问题是我使用位置语法来定义记录,而生成的自动 属性 不知道 XmlAttribute。但是,我可以通过明确说明如何生成 属性 来达到相同的效果。像这样:

public record Person (string Name, DateTime CreatedAt) {
    [XmlAttribute("dte_created")]
    public DateTime CreatedAt { get; init; } = CreatedAt;

    // parameterless ctor required for xml serializer
    public Person() : this(null, DateTime.MinValue) {}
}

在您的代码中,您将属性设置为构造函数参数

public record Person([XmlAttribute("dte_created")]DateTime CreatedAt);

您需要指示编译器使用 property::

在 属性 上设置属性
public record Person([property: XmlAttribute("dte_created")]DateTime CreatedAt);