如何定位记录类的属性?

Dan*_*ite 15 c# oop attributes c#-9.0 record-classes

定义记录类时,如何将属性定位到参数、字段或属性?

例如,我想使用,JsonIgnore但这不能编译,因为它对字段或属性有属性使用限制:

record Person(string FirstName, string LastName, [JsonIgnore] int Age);
Run Code Online (Sandbox Code Playgroud)

Dan*_*ite 28

要针对扩展类的各个部分,请使用适当的属性目标。例如:

// Target the property, use `property`
record Person(string FirstName, string LastName, [property: JsonIgnore] int Age);

// Target the backing field of the property, use `field`
record Person(string FirstName, string LastName, [field: JsonIgnore] int Age);

// Target the constructor parameter, use `param`
record Person(string FirstName, string LastName, [param: SomeParamAttribute] int Age);
Run Code Online (Sandbox Code Playgroud)

  • @dandev486 这是不明确的。某些属性仅适用于属性,否则会在编译时失败 (3认同)

KUT*_*ime 6

一个现实生活中的例子:

这条记录

public record GetAccountHolderParameters([property: JsonProperty("accountHolderCode")] string Code, [property: JsonProperty("showDetails")] bool ShowDetails);

Run Code Online (Sandbox Code Playgroud)

或者这个更容易阅读的首选语法

public record GetAccountHolderParameters(
    [property: JsonProperty("accountHolderCode")] string Code,
    [property: JsonProperty("showDetails")] bool ShowDetails
);

Run Code Online (Sandbox Code Playgroud)

相当于

public class GetAccountHolderParameters
{
    [JsonProperty(PropertyName = "accountHolderCode")]
    public string Code { get; set; }

    [JsonProperty(PropertyName = "showDetails")]
    public bool ShowDetails { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

关于 ASP.NET Core 请求参数的注意事项

您无法将验证属性应用于[property: ... ]请求参数,请参阅此问题

您将收到InvalidOperationException(...)

详情请参见本期