使用联合类型F#的所有情况

jle*_*ard 6 f#

这与此处的问题非常相关如何枚举F#中的枚举/类型.我定义了一个联合类型,然后我需要在静态方法中使用该类型的所有可能情况.例如:

type Interests =
| Music 
| Books
| Movies
    with 
        static member GetValue( this) = match this with 
                                         | Music  -> 0
                                         | Books -> 5
                                         | Movies -> 0
        static member GetSeqValues() = allCases|>Seq.map(GetValue)
Run Code Online (Sandbox Code Playgroud)

我如何获得allCases?

非常感谢

Tom*_*cek 12

您可以使用FSharpType.GetUnionCases()from Microsoft.FSharp.Reflection来获取所有受歧视联盟的案例.在您的示例中,它看起来像这样:

type Interests = 
   | Music  
   | Books 
   | Movies
   static member GetValue(this) = (...)
   static member GetSeqValues() = 
     // Get all cases of the union
     let cases = FSharpType.GetUnionCases(typeof<Interests>)
     [ for c in cases do 
         // Create value for each case (assuming it has no arguments)
         let interest = FSharpValue.MakeUnion(c, [| |]) :?> Interests
         yield GetValue(interest) ]
Run Code Online (Sandbox Code Playgroud)

但是,问题是你可能无法创建传递给你的GetValue成员的实例,因为有些情况下可能有参数(当MakeUnion你调用时必须传递一个参数数组而我只使用一个空数组).例如,如果你有:

type Sample =
 | A of int
 | B of bool
Run Code Online (Sandbox Code Playgroud)