Alternative for switch that only calls methods based on cases values

后端 未结 4 552
醉话见心
醉话见心 2021-01-19 03:59

Is there a possible way to write the next switch in some shorter, readable code?

switch (SomeValue)
{
  case \"001\": return DoMethod1(); break;
  case \"002         


        
4条回答
  •  悲&欢浪女
    2021-01-19 04:30

    There must be an error with your method definitions,

    class Program
    {
        static void Main()
        {
           var methods = new Dictionary>
               {
                   { "001", DoMethod1 }
               };
        }
    
        static int DoMethod1()
        {
            return 1;
        }
    }
    

    is perfectly valid syntax.

    but, this is not better than switch for 1 compelling and 1 subjective reason.

    If you are comparing against constants or literals then you should use switch. This enables the compiler to peform compile time optimizations without additional analysis.

    More subjectively, the dictionary/lookup approach is no shorter and I find it harder to read. However, it would be useful in situations where your comparison terms vary at runtime.

    If you want avoid rewriting the switch factor it into a function. Say,

    Func MethodsByValue(string value)
    {
        switch(value)
        {
            case "001":
                return DoMethod1;
    
            default:
                return DoMethod2;
        }
    }
    

    Either way,

    Rather than using some arbritary strings to enumerate your methods, why not use an enum? Then you will get additional performance and readability benefits.

提交回复
热议问题