在 F# 中将字节转换为枚举实例
让我们考虑一下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于基础类型为“int”的枚举,“enum”函数将执行转换,但对于非 int 枚举,您需要“LanguagePrimitives.EnumOfValue”,la:(
这里列出了 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:
(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 )
)
让 x : ScrollMode = 枚举模式
let x : ScrollMode = enum mode