简体   繁体   中英

How to get a case to reply with a case previously added in a switch in C#?

I have a question about switches in C#. I have a basic switch, three cases and a default, as you can see here:

string firstSwitch = Console.ReadLine().ToLower();
switch (firstSwitch)
{ 
    case "goodbye":
        Console.WriteLine("Hello, Goodbye");
        break;

    case "gandalf":
        Console.WriteLine("YOU SHALL NOT PASS!");
        break;

    case "skyrim":
        Console.WriteLine("I used to be an adventurer like you, then I took an arrow to the knee.");
        break;

    default:
        Console.WriteLine("The Force is strong with this one.");
        break;

Now I want to add another case that will respond with a random case output that was previously added. For example:

case "giveRandom":
    //Code that returns the value for Case 0, case 1, or case 2,//
    break;

Thanks in advance for your help guys.

Put all of your cases in a dictionary, and use this one in your switch statements:

var dict = new Dictionary<string, string>()
{
     new { "goodbye", "Hello, Goodbye" },
     new { "gandalf", "YOU SHALL NOT PASS!" },
     // etc
    new { "default", "The Force is strong with this one."}
};

string firstSwitch = Console.ReadLine().ToLower();
switch (firstSwitch)
{ 
    case "goodbye":
        Console.WriteLine(dict["goodbye"]);
        break;

    case "gandalf":
        Console.WriteLine(dict["gandalf"]);
        break;

    case "giveRandom":
        // choose a random element in dict and display it
        break;

    default:
        Console.WriteLine(dict["default"]);
        break;
}

For the random switch, you just take a random element out of the dictionary as described here .

In fact, you can maybe even reduce the number of switches like:

switch (firstSwitch)
{             
   case "giveRandom":
        // choose a random element in dict and display it
        break;

    default:
        if (dict.ContainsKey(firstSwitch))
        {
            Console.WriteLine(dict[firstSwitch]);
        }
        else
        {
             Console.WriteLine(dict["default"]);
        }
        break;
}

And as stated in the comments below, maybe you don't even need a switch (a simple if-then may suffice), but it depends on the logic that is involved.

if (firstSwitch == "giveRandom")
{
    // choose a random element in dict and display it
} 
else
{
     if (dict.ContainsKey(firstSwitch))
     {
          Console.WriteLine(dict[firstSwitch]);
     }
     else
     {
          Console.WriteLine(dict["default"]);
     }
}

And finally, also think about case sensitivity when comparing strings.

There is no syntax that will do what you want directly (especially since case is deterministic so there's no way to execute a "random" case), but what you want should be doable by thinking about it a different way. One way would be to put your cases in a List<string> and if giveRandom is selected then pick a string at random:

List<string> cases = new List<string> {"goodbye","gandalf","skyrim"};
string firstSwitch = Console.ReadLine().ToLower();

if(firstSwitch == "giveRandom")
{
    // if this method will be called in a tight loop 
    // then make rand a field of the class instead
    Random rand = new Random();

    // pick a case at random
    firstSwitch = cases[rand.Next(0, cases.Count)];
}

switch (firstSwitch)
{ 
    case "goodbye":
        Console.WriteLine("Hello, Goodbye");
        break;

    case "gandalf":
        Console.WriteLine("YOU SHALL NOT PASS!");
        break;

    case "skyrim":
        Console.WriteLine("I used to be an adventurer like you, then I took an arrow to the knee.");
        break;

    default:
        Console.WriteLine("The Force is strong with this one.");
        break;
}

You can do this with a SortedDictionary directly, and no switch statement:

readonly SortedDictionary<string, string> _nameLookup = new SortedDictionary<string, string>
{
    {"goodbye", "Hello, Goodbye"},
    {"gandalf", "YOU SHALL NOT PASS"},
    {"skyrim", "I used to be an adventurer . . ."},
    {"default", "The force is strong with this one."}
};
readonly Random _rand = new Random();

Then, in your function:

void foo()
{
    string firstSwitch = Console.ReadLine().ToLower();
    string result;
    if (firstSwitch == "chooserandom")
    {
        result = _nameLookup[_rand.Next(_nameLookup.Count)];
    }
    else if (!_nameLookup.TryGetValue(firstSwitch, out result))
    {
        result = _nameLookup["default"];
    }
    Console.WriteLine(result);
}

Granted, SortedDictionary is slower at lookup than Dictionary , but in a user interface application like this or if the number of options isn't huge, you'll never notice the difference. And selecting a random element here is easier and faster than with Dictionary .

This approach can also work well if you want to do more than just output a string. If you wanted to do a lot of processing for each item, you could replace the value in the dictionary with a method name (or an anonymous function). For example:

readonly SortedDictionary<string, Action> _nameDispatch = new SortedDictionary<string, Action>
{
    {"gandalf", ProcessGandalf},
    {"skyrim", ProcessSkyrim},
    // etc.
}

Of course, you'd need to define the methods ProcessGandalf , ProcessSkyrim , etc.

You'd use the same logic as above, but rather than writing the result, you'd have:

Action result;
// logic here to get the proper result.
// And then call that function:
result();

I think this is the way to go

  string firstSwitch = Console.ReadLine().ToLower();
            const string goodbye = "Hello, Goodbye";
            const string gandalf = "YOU SHALL NOT PASS!";
            const string skyrim = "I used to be an adventurer like you, then I took an arrow to the knee.";
            const string otherWise = "The Force is strong with this one.";
            switch (firstSwitch)
            {
                case "goodbye":
                    Console.WriteLine(goodbye);
                    break;

                case "gandalf":
                    Console.WriteLine(gandalf);
                    break;

                case "skyrim":
                    Console.WriteLine(skyrim);
                    break;
                case "giveRandom":
                    var dic = new Dictionary<int, string>();
                    dic[0] = goodbye;
                    dic[1] = gandalf;
                    dic[2] = skyrim;
                    var rnd = new Random();
                    Console.WriteLine(dic[rnd.Next(2, 0)]);
                    break;
                default:
                    Console.WriteLine(otherWise);
                    break;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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