“使用未分配的局部变量"C#中switch语句的编译器错误? [英] "Use of unassigned local variable" compiler error for switch statement in C#?

查看:34
本文介绍了“使用未分配的局部变量"C#中switch语句的编译器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 C# 代码:

I have the following C# code:

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

我在最后一行收到此错误:Use of unassigned local variable 'animal'.我知道这是因为 animal 可能没有取决于用户输入的值,那么我该如何解决呢?

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 (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语句的编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆