Multi-variable switch statement in C#

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

    Per the C# language specification, the switch statement expression must resolve to one of sbyte, byte, sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type. This means you cannot switch on Tuple or other higher-order types.

    You could try to pack the values together, assuming there is room. For example, suppose each of the integers is guaranteed to be in the range 0..9.

    switch (intVal1 * 100 + intVal2 * 10 + (boolVal3 ? 1 : 0))
    {
    case 100: /* intVal1 = 1, intVal2 = 0, boolVal3 = false */ ... break;
    case 831: /* intVal1 = 8, intVal2 = 3, boolVal3 = true */ ... break;
    }
    

提交回复
热议问题