C#9 不支持 JsonPropertyNameAttribute 记录?

Mak*_*luv 4 c# .net-5 system.text.json c#-9.0

我想使用带有 JsonPropertyName 属性的记录,但它导致了错误。这个不支持?任何解决方法?

public record QuoteResponse([JsonPropertyName("quotes")] IReadOnlyCollection<Quote>? Quotes);

Error CS0592 Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations.
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Yai*_*adt 16

默认情况下,记录参数的属性适用于参数。要将它们应用于属性,您必须使用property:属性位置作为前缀:

public record QuoteResponse([property: JsonPropertyName("quotes")] IReadOnlyCollection<Quote>? Quotes);
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 4

(据我所知)有两种方法可以创建记录,下面的方法有望为您解决。

public record QuoteResponse
{
    [JsonPropertyName("quotes")]
    public IReadOnlyCollection<Quote>? Quotes {get; init;}
}
Run Code Online (Sandbox Code Playgroud)

  • 如果没有 Set 或 Init 修饰符,该属性将不会被初始化。那么它和课堂上会有什么不同呢? (2认同)