Multi-variable switch statement in C#

后端 未结 12 503
-上瘾入骨i
-上瘾入骨i 2020-12-15 16:54

I would like use a switch statement which takes several variables and looks like this:

switch (intVal1, strVal2, boolVal3)
{
   case 1, \"hello\", false:
            


        
12条回答
  •  别那么骄傲
    2020-12-15 17:55

    Let's look at this another way. If you have:

    • Very specific combinations you want to check for;
    • No comparisons to do;
    • A default handler for every non-matching case;
    • All primitive/value types (int, bool, string, etc.)

    Then you can use a look-up table instead, which has a similar execution speed to the switch statement but not quite as efficient (since it needs to calculate hashes). Still, it's probably good enough. And it gives you the opportunity to name cases, to make this combinatorial explosion slightly less confusing and unmaintainable.

    A code example:

    private static readonly Tuple NameOfCase1 = 
        Tuple.Create(1, 1, false);
    private static readonly Tuple NameOfCase2 =
        Tuple.Create(2, 1, false);
    private static readonly Tuple NameOfCase3 =
        Tuple.Create(2, 2, false);
    
    private static readonly Dictionary, string> Results =
        new Dictionary, string>
    {
        { NameOfCase1, "Result 1" },
        { NameOfCase2, "Result 2" },
        { NameOfCase3, "Result 3" }
    };
    
    public string GetResultForValues(int x, int y, bool b)
    {
        const string defaultResult = "Unknown";
        var lookupValue = Tuple.Create(x, y, b);
        string result;
        Results.TryGetValue(lookupValue, out result);
        return defaultResult;
    }
    

    If you need to actually execute a function or method for each case then you can use a result type (dictionary value) of Action or Func instead.

    Note that I'm using Tuple here because it already has all of the hash code logic built in. The syntax is a little awkward in C# but if you want, you can implement your own lookup class and just override Equals and GetHashCode.

提交回复
热议问题