gpt4 book ai didi

reflection - F#:受歧视联合字段的属性?

转载 作者:行者123 更新时间:2023-12-04 17:54:25 25 4
gpt4 key购买 nike

我能做到:

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 ()),所以我希望这是可行的。

最佳答案

这是相当做作的:

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

关于reflection - F#:受歧视联合字段的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41626032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com