Getting the max value of an enum

后端 未结 11 2243
旧时难觅i
旧时难觅i 2020-12-07 13:42

How do you get the max value of an enum?

11条回答
  •  时光说笑
    2020-12-07 14:01

    In F#, with a helper function to convert the enum to a sequence:

    type Foo =
        | Fizz  = 3
        | Bang  = 2
    
    // Helper function to convert enum to a sequence. This is also useful for iterating.
    // stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values-c
    let ToSeq (a : 'A when 'A : enum<'B>) =
        Enum.GetValues(typeof<'A>).Cast<'B>()
    
    // Get the max of Foo
    let FooMax = ToSeq (Foo()) |> Seq.max   
    

    Running it...

    > type Foo = | Fizz = 3 | Bang = 2
    > val ToSeq : 'A -> seq<'B> when 'A : enum<'B>
    > val FooMax : Foo = Fizz
    

    The when 'A : enum<'B> is not required by the compiler for the definition, but is required for any use of ToSeq, even by a valid enum type.

提交回复
热议问题