Multi-variable switch statement in C#

后端 未结 12 505
-上瘾入骨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:54

    I do this kind of thing with lists or arrays. If you can enumerate the possible conditions (which you obviously can if you're wanting to do a multi-value switch), then build a lookup table with a multi-part key and an Action or Func as the value.

    A simple version would use a Dictionary:

    class LookupKey: IComparable
    {
        public int IntValue1 { get; private set; }
        public int IntValue2 { get; private set; }
        public bool BoolValue1 { get; private set; }
        public LookupKey(int i1, int i2, bool b1)
        {
            // assign values here
        }
        public int Compare(LookupKey k1, LookupKey k2)
        {
            return k1.IntValue1 == k2.IntValue1 &&
                   k1.IntValue2 == k2.IntValue2 &&
                   k1.BoolValue1 == k2.BoolValue1;
        }
        public int GetHashCode()
        {
            return (19 * IntValue1) + (1000003 * IntValue2) + (BoolValue1) ? 0 : 100000073;
        }
        // need to override Equals
    }
    

    And your dictionary:

    static readonly Dictionary> LookupTable;
    

    You can then populate the dictionary at startup, and then a lookup becomes a simple matter of:

    Action MethodToCall;
    if (LookupTable.TryGetValue(new LookupKey(i1, i2, b1), out MethodToCall)
        MethodToCall(theData);
    else
        // default action if no match
    
    
    

    It's a bit of code to set up, but it's very quick in execution.

    提交回复
    热议问题