I have a class with an enum property. To use the compact property syntax I have to initialize it with a value from the type, eg.

type Color = 
    | Blue= 0
    | Green= 1

type MyClass() =
    member val Col = Color.Blue with get, set // <-- the problem

However, I don't like the hard coded Blue in there, and would prefer to set it to the first item of the enumeration.

I've been able to do it with this:

member val Color = enum<Color>(unbox (Enum.GetValues(typeof<Color>).GetValue(0))) ...

Needless to say, I'm hoping there's a better way to either get the first value of an enum, or initialize the property!

有帮助吗?

解决方案 2

Given the two alternatives you mention, I believe you are better off with Color.Blue. While the numeric values backing the enumeration are entirely arbitrary, the colours at least have some meaning in your application. If you are uncomfortable with setting the value directly because there is extra meaning associated to the default you can always define it separately somewhere else:

let standardUniformColor = Color.Blue
//(...)
type MyClass() = member val Col = standardUniformColor with get, set

其他提示

If the first member is significant within your program then it makes sense to make it explicit. It's perfectly fine to have two members with the same value.

type Color    = 
    | Default = 0
    | Blue    = 0
    | Green   = 1

type MyClass() =
    member val Col = Color.Default with get, set

Since enum equality depends on the underlying value, this works as desired (i.e., prints "blue"):

let c = MyClass()
match c.Col with
| Color.Blue -> printfn "blue"
| _ -> printfn "not blue"

You can use the magic enum function like so:

type Color =
    | Blue= 0
    | Green= 1

type MyClass() =
    member val Col : Color = enum 0 with get, set 

The only catch is that you need a type annotation somewhere so that the compiler knows which enum to cast to.

NOTE: This assumes that the enum's first value is 0.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top