简体   繁体   English

C#中的switch语句“使用未分配的局部变量”编译器错误?

[英]“Use of unassigned local variable” compiler error for switch statement in C#?

I have the following C# code: 我有以下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' . 我在最后一行收到此错误: 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? 我知道这是因为animal可能没有值,具体取决于用户输入,因此该如何解决?

Ideally I'd like to show an error message if an unknown animal type was entered and make the user input the value again. 理想情况下,如果输入了未知的动物类型,我想显示一条错误消息,并让用户再次输入该值。

Thanks. 谢谢。

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);
}

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. 我还将注意到,使用if (s.Equals("dog", StringComparison.CurrentCultureIgnoreCase)) (或适当的不区分大小写的比较)将其重构为一个if / else链是一种很好的做法,其他文化。 Of course, this may not apply to your scenario (eg test/homework app, or something that will only possibly be used in your culture). 当然,这可能不适用于您的方案(例如,测试/家庭作业应用程序,或仅在您的文化中可能使用的某些应用程序)。


Update: Thanks to Mennan Kara for the idea, if your values (eg "dog" ) will always match the enum's values (eg DOG ), then you can use Enum.TryParse to improve your code: 更新:感谢Mennan Kara的想法,如果您的值(例如"dog" )始终与枚举的值(例如DOG )匹配,则可以使用Enum.TryParse来改进代码:

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. 如果需要将它们分开的灵活性,请保留现有的开关。

In case s.ToLower() is something else that dog , cat or rabbit , animal has no value. 如果s.ToLower()dogcatrabbitanimal没有任何价值。

You should add default in your switch for that case: 对于这种情况,您应该在交换机中添加默认值:

switch (s.ToLower())
{
case "dog":
    animal = AnimalTypeEnum.DOG;
    break;
case "cat":
    animal = AnimalTypeEnum.CAT;
    break;
case "rabbit":
    animal = AnimalTypeEnum.RABBIT;
    break;
default:
    animal = ...
    break;
}
AnimalTypeEnum animal;
var s = Console.ReadLine();
Console.WriteLine(!Enum.TryParse(s, true, out animal) ? "Not a valid animal" : animal.ToString());

You should have a default ENUM for any animal unknown to your code . 您应该为代码未知的任何动物设置默认的ENUM You could even make your code to learn new animals. 您甚至可以编写代码来学习新动物。 For instance. 例如。

switch (s.ToLower())
{
default:
    animal = AnimalType.Unkown;
    break;
}

or 要么

default:
    animal = new MakeEnum(s.ToLower());
    myEnumList.Add(animal);
    break;

Your MakeEnum basically just needs to check length of current number of enums, and make a new enum using the number or some other parameter. 您的MakeEnum基本上只需要检查当前枚举数的长度,并使用number或其他一些参数创建一个新的枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM