问题描述
我有以下C#代码:
AnimalTypeEnum animal;
string s = Console.ReadLine();
switch (s.ToLower())
{
case "dog":
animal = AnimalTypeEnum.DOG;
break;
case "cat":
animal = AnimalTypeEnum.CAT;
break;
case "rabbit":
animal = AnimalTypeEnum.RABBIT;
break;
}
Console.WriteLine(animal); #compiler error here
我在最后一行收到此错误:使用未分配的局部变量'动物'
。我知道这是因为动物
可能没有取决于用户输入的值,那么我该如何解决呢?
I get this error on the last line: Use of unassigned local variable 'animal'
. I know that it's because animal
may not have a value depending on the user input, so how do I fix that?
理想情况下,如果输入了未知的动物类型,我想显示错误消息,并使用户再次输入值。
Ideally I'd like to show an error message if an unknown animal type was entered and make the user input the value again.
谢谢。
推荐答案
这是一种解决方法,使用递归调用而不是需要捕获和抛出例外或使用循环(在这种情况下,循环在我看来模糊了意义;太多关于你如何做,而不是你在做什么):
Here's one way to fix it, using recursive calls instead of needing to catch and throw exceptions, or use a loop (loops in a case like this obfuscate the meaning in my opinion; too much about how you're doing it instead of what you're doing):
private static AnimalTypeEnum GetAnimalFromInput()
{
AnimalTypeEnum animal;
string s = Console.ReadLine();
switch (s.ToLower())
{
case "dog":
animal = AnimalTypeEnum.DOG;
break;
case "cat":
animal = AnimalTypeEnum.CAT;
break;
case "rabbit":
animal = AnimalTypeEnum.RABBIT;
break;
default:
Console.WriteLine(s + " is not valid, please try again");
animal = GetAnimalFromInput();
break;
}
return animal;
}
static void Main(string[] args)
{
AnimalTypeEnum animal = GetAnimalFromInput();
Console.WriteLine(animal);
}
我还会注意到,将您的切换重构为if / else链,使用 if(s.Equals(dog,StringComparison.CurrentCultureIgnoreCase))
(或适当的不区分大小写的比较),以使其在其他文化中工作。当然,这可能不适用于您的场景(例如,测试/功课应用程序,或只能在您的文化中使用的东西)。
I'll also note that it's good practice to refactor your switch into an if/else chain, using if (s.Equals("dog", StringComparison.CurrentCultureIgnoreCase))
(or the appropriate case-insensitive comparison) to keep it working in other cultures. Of course, this may not apply to your scenario (e.g. test/homework app, or something that will only possibly be used in your culture).
更新:感谢Mennan Kara的想法,如果您的值(例如dog
)将始终匹配枚举值(例如 DOG
),则可以使用 Enum.TryParse
来改善代码:
Update: Thanks to Mennan Kara for the idea, if your values (e.g. "dog"
) will always match the enum's values (e.g. DOG
), then you can use Enum.TryParse
to improve your code:
private static AnimalTypeEnum GetAnimalFromInput()
{
AnimalTypeEnum animal;
string s = Console.ReadLine();
if (Enum.TryParse(s, true, out animal))
return animal;
else
{
Console.WriteLine(s + " is not valid, please try again");
return GetAnimalFromInput();
}
}
如果您需要将它们分开的灵活性,保留现有的开关。
If you need the flexibility of having them separate, then keep your existing switch.
这篇关于“使用未分配的局部变量” C#中switch语句的编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!