簡體   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