我在 F# 中有一个枚举,如下所示:
type Creature =
| SmallCreature = 0
| MediumCreature = 1
| GiantCreature = 2
| HumongousCreature = 3
| CreatureOfNondescriptSize = 4
我不喜欢手动输入数字,并且希望稍后可以轻松地在枚举中插入更多项目,而无需移动数字。
我试过这个
type Creature =
| SmallCreature
| MediumCreature
| GiantCreature
| HumongousCreature
| CreatureOfNondescriptSize
但这导致了错误The type 'Creature' is not a CLI enum type
稍后在节目中
let input = Int32.Parse(Console.ReadLine())
let output = match EnumOfValue<int, Creature>(input) with // <---Error occurs here
| Creature.SmallCreature -> "Rat"
| Creature.MediumCreature -> "Dog"
| Creature.GiantCreature -> "Elephant"
| Creature.HumongousCreature -> "Whale"
| Creature.CreatureOfNondescriptSize -> "Jon Skeet"
| _ -> "Unacceptably Hideous Monstrosity"
Console.WriteLine(output)
Console.WriteLine()
Console.WriteLine("Press any key to exit...")
Console.Read() |> ignore
如何定义枚举而不手动为每个项目分配数值?
不幸的是,你不能。数值重要吗?如果是这样,它在某种程度上就逃脱了枚举的预期用途(除了标志)。在这种情况下,您可能会考虑阶级或歧视工会。
事实上,你的第二个例子是一个受歧视的工会。但你以后使用EnumOfValue
需要枚举,导致了错误。
另一种选择是将枚举到数字的映射存储在字典中,并用字典查找替换模式匹配。那么,枚举的数值就无关紧要了。
我同意手动管理枚举值是很繁重的。我希望它能在未来的版本中得到解决。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)