问题
When defining a record class, how do I target the attributes to the parameter, field or property?
For instance, I would like to use JsonIgnore
but this doesn't compile as it has an attribute usage restriction to the field or property:
record Person(string FirstName, string LastName, [JsonIgnore] int Age);
回答1:
To target the various parts of the expanded class, use the appropriate attribute target. For instance:
// 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);
来源:https://stackoverflow.com/questions/63778276/how-do-i-target-attributes-for-a-record-class