我有一个枚举如下
type Suit =
|Clubs = 'C'
|Spades = 'S'
|Hearts = 'H'
|Diamonds = 'D'
如果给定枚举值,如何获取基础char值?
例如,我有Suit.Clubs
并希望得到'C'
答案 0 :(得分:15)
作为另一种选择
type Suit =
|Clubs = 'C'
|Spades = 'S'
|Hearts = 'H'
|Diamonds = 'D'
let c = Suit.Clubs
let v : char = LanguagePrimitives.EnumToValue c
EDITED: 不同方法的比较:
type Suit =
|Clubs = 'C'
|Spades = 'S'
|Hearts = 'H'
|Diamonds = 'D'
let valueOf1 (e : Suit) = LanguagePrimitives.EnumToValue e
let valueOf2 (e : Suit) = unbox<char> e
let valueOf3 (e : Suit) = (box e) :?> char
并在引擎盖下:
.method public static
char valueOf1 (
valuetype Program/Suit e
) cil managed
{
// Method begins at RVA 0x2050
// Code size 3 (0x3)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ret
} // end of method Program::valueOf1
.method public static
char valueOf2 (
valuetype Program/Suit e
) cil managed
{
// Method begins at RVA 0x2054
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box Program/Suit
IL_0007: unbox.any [mscorlib]System.Char
IL_000c: ret
} // end of method Program::valueOf2
.method public static
char valueOf3 (
valuetype Program/Suit e
) cil managed
{
// Method begins at RVA 0x2064
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box Program/Suit
IL_0007: unbox.any [mscorlib]System.Char
IL_000c: ret
} // end of method Program::valueOf3
答案 1 :(得分:6)
您可以使用LanguagePrimitives
模块中的功能:
// Convert enum value to the underlying char value
let ch = LanguagePrimitives.EnumToValue Suit.Clubs
// Convert the char value back to enum
let suit = LanguagePrimitives.EnumOfValue ch
编辑:我在第一次尝试回答时没有看到这些功能,所以我首先建议使用:
unbox<char> Suit.Clubs
这比 ildjarn 在评论中建议的要短,但它有同样的问题 - 没有检查你实际上是否转换为正确的类型。使用EnumToValue
,您不能犯这个错误,因为它总是返回正确的基础类型的值。