简体   繁体   English

F#:区分的联合字段上的属性?

[英]F#: Attributes on discriminated union fields?

I can do this: 我可以做这个:

type AttrAttribute () =
    inherit Attribute ()

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

... but is there any way to do this? ...但是有什么办法吗?

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

Apparently, the case values are just fields (eg let v = B (13, "oops") in (Microsoft.FSharp.Reflection.FSharpValue.GetUnionFields (v, v.GetType ()) |> fst).GetFields () ), so I'm hoping this is doable, somehow. 显然,大小写值只是let v = B (13, "oops") in (Microsoft.FSharp.Reflection.FSharpValue.GetUnionFields (v, v.GetType ()) |> fst).GetFields ()字段(例如, let v = B (13, "oops") in (Microsoft.FSharp.Reflection.FSharpValue.GetUnionFields (v, v.GetType ()) |> fst).GetFields () ) ,所以我希望这是可行的。

This is quite contrived: 这是非常人为的:

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

type MyDU =
    | A of A_
    | B of B_

And

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

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

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