繁体   English   中英

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

[英]Custom attribute on record fields F#

我正在尝试在记录中声明自定义属性并尝试读取它。 它似乎不起作用。 请指教。

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

下面的代码解决了这个问题。 有关更详细的答案,请参阅此链接

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