简体   繁体   English

记录字段上的自定义属性 F#

[英]Custom attribute on record fields F#

I am trying to declare a custom attribute in a record and trying to read it.我正在尝试在记录中声明自定义属性并尝试读取它。 It seems to be not working.它似乎不起作用。 Please advise.请指教。

// Custom Attribute for record fields
[<AttributeUsage(AttributeTargets.Field)>]
type Name(x: string) =
    inherit Attribute()
    member _.value = x

// Record type
type User =
    { [<Name("id")>]
      Id: int
      [<Name("email")>]
      Email: string
      [<Name("organization_id")>]
      OrganizationId: option<string> }

// Trying to read the attribute. This is not working. I am getting <null> here.
let parse () =
    FSharpType.GetRecordFields(typeof<User>)
    |> Array.map (fun p -> p.Name, p.GetCustomAttribute(typeof<Name>, false))
    |> Array.iter (fun (t, a) -> printfn "%s : %A" t a)

The below code fixes the problem.下面的代码解决了这个问题。 For more detailed answer, refer this link .有关更详细的答案,请参阅此链接

// Changing to property instead of field
[<AttributeUsage(AttributeTargets.Property)>]
type Name(x: string) =
    inherit Attribute()
    member _.value = x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM