Ale*_*lex 1 c# enums constants switch-statement
嗨,我有一个简单的问题,但是一直困扰我一段时间.
题:
在C#中使用switch语句时,使用enumsover constants或者反之亦然?或者这是一个偏好的问题?我问这个是因为很多人似乎喜欢使用enums,但是当你打开一个int值时,你必须将每个包含的值转换enum成一个int,即使你指定了它的类型enum.
代码片段:
class Program
{
enum UserChoices
{
MenuChoiceOne = 1,
MenuChoiceTwo,
MenuChoiceThree,
MenuChoiceFour,
MenuChoiceFive
}
static void Main()
{
Console.Write("Enter your choice: ");
int someNum = int.Parse(Console.ReadLine());
switch (someNum)
{
case (int)UserChoices.MenuChoiceOne:
Console.WriteLine("You picked the first choice!");
break;
// etc. etc.
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以创建一个实例enum并将整个enum转换为int?
谢谢!
Mar*_*ers 10
为什么不这样做呢?
UserChoices choice = (UserChoices)int.Parse(Console.ReadLine());
switch (choice)
{
case UserChoices.MenuChoiceOne:
// etc...
Run Code Online (Sandbox Code Playgroud)
然后你只需要施放一次.
更新:修复代码中的错误!