Multi-variable switch statement in C#

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

    My downright crazy take on this:

    class Program
    {
        static void Main(string[] args)
        {
            var i = 1;
            var j = 34;
            var k = true;
            Match(i, j, k).
                With(1, 2, false).Do(() => Console.WriteLine("1, 2, 3")).
                With(1, 34, false).Do(() => Console.WriteLine("1, 34, false")).
                With(x => i > 0, x => x < 100, x => x == true).Do(() => Console.WriteLine("1, 34, true"));
    
        }
    
        static Matcher Match(T1 t1, T2 t2, T3 t3)
        {
            return new Matcher(t1, t2, t3);
        }
    }
    
    public class Matcher
    {
        private readonly object[] values;
    
        public object[] Values
        {
            get { return values; }
        }
    
        public Matcher(T1 t1, T2 t2, T3 t3)
        {
            values = new object[] { t1, t2, t3 };
        }
    
        public Match With(T1 t1, T2 t2, T3 t3)
        {
            return new Match(this, new object[] { t1, t2, t3 });
        }
    
        public Match With(Func t1, Func t2, Func t3)
        {
            return new Match(this, t1, t2, t3);
        }
    }
    
    public class Match
    {
        private readonly Matcher matcher;
        private readonly object[] matchedValues;
        private readonly Func matcherF; 
    
        public Match(Matcher matcher, object[] matchedValues)
        {
            this.matcher = matcher;
            this.matchedValues = matchedValues;
        }
    
        public Match(Matcher matcher, Func t1, Func t2, Func t3)
        {
            this.matcher = matcher;
    
    
            matcherF = objects => t1((T1)objects[0]) && t2((T2)objects[1]) && t3((T3)objects[2]);
        }
    
        public Matcher Do(Action a)
        {
            if(matcherF != null && matcherF(matcher.Values) || matcher.Values.SequenceEqual(matchedValues))
                a();
    
            return matcher;
        }
    }
    

提交回复
热议问题