F#:有区别的联合字段的属性?

时间:2017-01-13 01:30:32

标签: reflection f# discriminated-union

我可以这样做:

type AttrAttribute () =
    inherit Attribute ()

type MyDU =
    | [<Attr>]A of bool
    | [<Attr>]B of int * string
    | [<Attr>]C of byte * char * int64

......但有没有办法做到这一点?

type MyDU =
    | A of [<Attr>]bool
    | B of int * [<Attr>]string
    | C of [<Attr>]byte * char * [<Attr>]int64

显然,案例值只是字段(例如let v = B (13, "oops") in (Microsoft.FSharp.Reflection.FSharpValue.GetUnionFields (v, v.GetType ()) |> fst).GetFields ()),所以我希望这是可行的,不知何故。

1 个答案:

答案 0 :(得分:0)

这是非常人为的:

type A_ = { [<Attr>] Item1 : int }
type B_ = { [<Attr>] Item1 : int; [<Attr>] Item2 : string }

type MyDU =
    | A of A_
    | B of B_

并且

let v = A({Item1 = 1})
let record = ((FSharpValue.GetUnionFields (v, v.GetType ()) |> fst).GetFields ()) |> Array.head 
let attrs = record.PropertyType.GetProperties() |> Array.collect(fun p -> p.GetCustomAttributes(false))