在 F# 中将字节转换为枚举实例

发布于 2024-07-19 05:24:18 字数 348 浏览 1 评论 0原文

让我们考虑一下 C# 中的以下枚举

public enum ScrollMode : byte
{
      None = 0,
      Left = 1,
      Right = 2,
      Up = 3,
      Down = 4
}

F# 代码接收一个字节并且必须返回枚举的实例 我已经尝试过

let mode = 1uy
let x = (ScrollMode)mode

(当然在实际应用程序中我无法设置“模式”, 它作为网络数据的一部分被接收)。

上面的例子无法编译,有什么建议吗?

Let's consider the following enum in C#

public enum ScrollMode : byte
{
      None = 0,
      Left = 1,
      Right = 2,
      Up = 3,
      Down = 4
}

The F# code receives a byte and has to return an instance of the enum
I have tried

let mode = 1uy
let x = (ScrollMode)mode

(Of course in the real application I do not get to set 'mode',
it is received as part of network data).

The example above does not compile, any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山川志 2024-07-26 05:24:18

对于基础类型为“int”的枚举,“enum”函数将执行转换,但对于非 int 枚举,您需要“LanguagePrimitives.EnumOfValue”,la:(

// define an enumerated type with an sbyte implementation
type EnumType =
  | Zero = 0y
  | Ten  = 10y

// examples to convert to and from
let x = sbyte EnumType.Zero
let y : EnumType = LanguagePrimitives.EnumOfValue 10y

这里列出了 EnumOfValue

http://research.microsoft. com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.LanguagePrimitives.html

(现在 http://msdn.microsoft.com/en-us/library/ee340276(VS.100).aspx )

而此处列出了枚举

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html

(现在 http://msdn.microsoft.com/en-us/library/ee353754 (VS.100).aspx)

For enums whose underlying type is 'int', the 'enum' function will do the conversion, but for non-int enums, you need 'LanguagePrimitives.EnumOfValue', a la:

// define an enumerated type with an sbyte implementation
type EnumType =
  | Zero = 0y
  | Ten  = 10y

// examples to convert to and from
let x = sbyte EnumType.Zero
let y : EnumType = LanguagePrimitives.EnumOfValue 10y

(EnumOfValue is listed here

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.LanguagePrimitives.html

(now http://msdn.microsoft.com/en-us/library/ee340276(VS.100).aspx )

whereas enum is listed here

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html

(now http://msdn.microsoft.com/en-us/library/ee353754(VS.100).aspx )
)

原来分手还会想你 2024-07-26 05:24:18

让 x : ScrollMode = 枚举模式

let x : ScrollMode = enum mode

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文