gpt4 book ai didi

f# - 将 Enum 转换为基础类型

转载 作者:行者123 更新时间:2023-12-03 23:46:49 25 4
gpt4 key购买 nike

我有一个枚举如下

type Suit =
|Clubs = 'C'
|Spades = 'S'
|Hearts = 'H'
|Diamonds = 'D'

如果给定枚举值,我如何获得基础字符值?
例如我有 Suit.Clubs并想获得“C”

最佳答案

作为另一种选择

type Suit =
|Clubs = 'C'
|Spades = 'S'
|Hearts = 'H'
|Diamonds = 'D'

let c = Suit.Clubs
let v : char = LanguagePrimitives.EnumToValue c

编辑:
不同方法的比较:
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

关于f# - 将 Enum 转换为基础类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9072500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com