如何重构这些 switch case 以处理自然语言中的用户选择?

How to refactor these switch cases to handle user choice in natural language?(如何重构这些 switch case 以处理自然语言中的用户选择?)

本文介绍了如何重构这些 switch case 以处理自然语言中的用户选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写几个嵌套的 switch 语句,在某些地方有很多情况.

I'm writing several nested switch statements with quite a few cases in some spots.

我正在尝试找出一种方法来创建一个案例列表,然后在以后的 switch 语句中引用.

I'm trying to figure out a way to create a list of cases to then be referenced in later switch statements.

有没有办法做到这一点?

Is there a way to do this?

它肯定会清理我的代码.

It would certainly clean up my code.

例如,我有四个不同的是"案例.回答.

For example, I have four separate cases for a "yes" answer.

我正在寻找一种方法将这四种情况存储在一个变量中,并在每次我想在 switch 中使用它们时调用该变量.

I am looking for a way to store these four cases in a variable and call on that variable each time I want to use them in a switch.

Console.Write("
Were you feeling exhausted? ");
response = Console.ReadLine().ToLower();
Console.Clear();
switch (response)
{
    case "yes":
    case "y":
    case "yep":
    case "yeah":
        {
            goto ThreeTwo;
        }
    case "no":
    case "n":
    case "nope":
    case "nah":

推荐答案

一个很好的干净方法是首先声明一个 enum 来表示答案值.它将需要是"、否"未定义"(后者表示既不是是"也不是否"的答案):

A nice clean way to do this is first to declare an enum to represent the answer values. It will need "Yes", "No" and "Undefined" (the latter to represent an answer which is neither "Yes" nor "No"):

public enum YesOrNo
{
    Undefined,
    Yes,
    No
}

然后您可以将是/否检测逻辑包装在一个类中.有很多方法可以做到这一点;这是一个简单的(你可以用字典代替,但对于这么少的字符串,它不是真的必要,我试图让它尽可能简单):

Then you can wrap the yes/no detection logic in a class. There are many ways to do this; here's a simple one (you could use a dictionary instead, but for such a small number of strings it's not really necessary, and I'm trying to keep this as simple as possible):

public static class YesOrNoDetector
{
    static readonly string[] _yesAnswers = { "yes", "y", "yep", "yeah", "affirmative" };
    static readonly string[] _noAnswers  = { "no",  "n", "nah", "nope", "negative"    };

    public static YesOrNo Detect(string answer)
    {
        if (_yesAnswers.Contains(answer.ToLower()))
            return YesOrNo.Yes;

        if (_noAnswers.Contains(answer.ToLower()))
            return YesOrNo.No;

        return YesOrNo.Undefined;
    }
}

(注意它如何在比较之前通过将字符串转换为小写来处理大写答案.)

(Note how it also handles uppercase answers by converting the string to lowercase before comparing.)

然后你的原始代码变成这样:

Then your original code becomes something like:

switch (YesOrNoDetector.Detect(response))
{
    case YesOrNo.Yes:
    {
        goto ThreeTwo;  // Please get rid of this goto!
    }

    case YesOrNo.No:
    {
        // Handle "No".
        break;
    }

    case YesOrNo.Undefined:
    {
        // Handle incorrect answer.
        break;
    }
}

这篇关于如何重构这些 switch case 以处理自然语言中的用户选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何重构这些 switch case 以处理自然语言中的用户选择?

基础教程推荐