我在F#中有一个枚举,像这样:
type Creature =
| SmallCreature = 0
| MediumCreature = 1
| GiantCreature = 2
| HumongousCreature = 3
| CreatureOfNondescriptSize = 4
Run Code Online (Sandbox Code Playgroud)
我不喜欢手动输入数字,我想稍后在枚举中轻松插入更多项目,而不必移动数字.
我试过这个
type Creature =
| SmallCreature
| MediumCreature
| GiantCreature
| HumongousCreature
| CreatureOfNondescriptSize
Run Code Online (Sandbox Code Playgroud)
但它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
Run Code Online (Sandbox Code Playgroud)
如何在不手动为每个项目分配数值的情况下定义枚举?
不幸的是,你做不到.数值是否重要?如果是这样,它有点逃避枚举的预期用途(标记旁边).在这种情况下,你可以考虑一个阶级或有区别的联盟.
事实上,你的第二个例子是一个受歧视的联盟.但是你后来使用的EnumOfValue,它需要一个枚举,导致错误.
另一种选择是将枚举存储到字典中的数字映射,并将模式匹配替换为字典查找.然后,枚举的数值将是无关紧要的.
我同意手动管理枚举值很麻烦.我希望它在未来版本中得到解决.