Multi-variable switch statement in C#

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

    There is (was) no built-in functionality to do this in C#, and I don't know of any library to do this.

    Here is an alternative approach, using Tuple and extension methods:

    using System;
    
    static class CompareTuple {
        public static bool Compare(this Tuple value, T1 v1, T2 v2, T3 v3) {
            return value.Item1.Equals(v1) && value.Item2.Equals(v2) && value.Item3.Equals(v3); 
        }
    }
    
    class Program {
        static void Main(string[] args) {
            var t = new Tuple(1, 2, false);
            if (t.Compare(1, 1, false)) {
                // 1st case
            } else if (t.Compare(1, 2, false)) {
                // 2nd case
            } else { 
                // default
            }
        }
    }
    

    This is basically doing nothing more than providing a convenient syntax to check for multiple values - and using multiple ifs instead of a switch.

提交回复
热议问题