c# switch statement is return suitable to replace break

后端 未结 2 1174
刺人心
刺人心 2020-12-09 15:04

Is this an appropriate way to handle c# switch statements or is an explicit break required still? reference

  public static string ToRegistryString(AliceK         


        
2条回答
  •  攒了一身酷
    2020-12-09 15:40

    That's fine. The point is that the end of a case block should be unreachable - which it is here, because you've returned.

    Why are you returning new string(new char[0]) rather than just "" or string.Empty though? If you're trying to make sure it's a different string each time, you'll actually run into a very weird corner case - despite calling new string(...) that code will always actually return the same reference...

    Finally: I would actually suggest changing this switch/case block into just a Dictionary:

    private static readonly Dictionary RegistryMap =
        new Dictionary
    {
        { AliceKey.AliceKeyPaths.NET_CLR_DATA, @"\.NET CLR Data\" },
        { AliceKey.AliceKeyPaths.NET_CLR_NETWORKING, @"\.NET CLR Networking\" },
        // etc
    };
    
    public static string ToRegistryString(AliceKey.AliceKeyPaths aliceKeyPath)
    {
        string value;
        return RegistryMap.TryGetValue(aliceKeyPath, out value) ? value : "";
    }
    

提交回复
热议问题