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)
这条记录
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)
您无法将验证属性应用于[property: ... ]请求参数,请参阅此问题。
您将收到InvalidOperationException(...)。
详情请参见本期。
| 归档时间: |
|
| 查看次数: |
759 次 |
| 最近记录: |