【问题标题】:How do I target attributes for a record class?如何定位记录类的属性?
【发布时间】:2020-09-07 13:10:09
【问题描述】:

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

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

record Person(string FirstName, string LastName, [JsonIgnore] int Age);

【问题讨论】:

  • @HimBromBeere 是的。记录在构造函数行中定义属性
  • 你也可以用一个类而不是record来重现你的问题。
  • @HimBromBeere 当然,但是随着越来越多的人采用 DTO 的记录类,这个问题将会出现。在类的情况下,您有明确定义的属性,它与记录结合使用构造函数参数

标签: c# oop attributes c#-9.0 record-classes


【解决方案1】:

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

// 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);

【讨论】:

  • Daniel,你知道为什么我们必须指定property 目标,即使int Age 成为结果记录中的一个属性吗?
  • @dandev486 这是模棱两可的。某些属性仅适用于属性,否则它会在编译时失败
  • 我注意到 if 在编译时失败,但在我看来,编译器在使用记录的位置语法时假设默认情况下未指定的目标意味着属性是有意义的,因为它旨在用于生成属性。在这种特定情况下,JsonIgnore 实际上有多个目标,但是当属性仅针对属性时也会发生编译器错误。无论如何,感谢您分享您的想法! :]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2019-02-01
相关资源
最近更新 更多