简体   繁体   English

如何在 F# 中为枚举指定基础类型

[英]how to specify an underlying type for enum in F#

We can specify an underlying type for enum in C# like this:我们可以在 C# 中为枚举指定一个底层类型,如下所示:

[Flags]
public enum MyKinds : ushort
{
    None  = 0,
    Flag1 = 1 << 0,
    Flag2 = 1 << 1,
    // ...
}
  1. How can I do that using F#?如何使用 F# 做到这一点?
type MyKinds = 
    | None  = 0 
    | Flag1 = 1
    | Flag2 = 2

    // inherit ushort  // error FS0912
  1. How can I define enum values using bitwise operator like 1 << 0 in F#?如何使用 F# 中的1 << 0之类的按位运算符定义枚举值?
type MyKinds = 
    | None = 0 
    | Flag1 = 1 << 0    // error FS0010
    | Flag2 = 1 << 1    // error FS0010

You can't use bit shifting, but isn't this even better?你不能使用位移,但这不是更好吗?

type MyKinds = 
    | None =  0b0000us
    | Flag1 = 0b0001us
    | Flag2 = 0b0010us

Also, if these are to be used as bit flags, you might want to add the [<Flag>] attribute, so that printing the value will show any combination of flags.此外,如果这些要用作位标志,您可能需要添加[<Flag>]属性,以便打印该值将显示标志的任何组合。

As specified in The Docs , the underlying type of an enum in F# is determined by the numerical suffix.The Docs中所述,F# 中枚举的基础类型由数字后缀确定。
So in your case, for ushort (unit16), it would be:因此,在您的情况下,对于 ushort (unit16),它将是:

type MyKinds = 
    | None  = 0us 
    | Flag1 = 1us
    | Flag2 = 2us

(suffixes for different number types available Here ) 此处提供不同数字类型的后缀)

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

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