C#中的switch语句使用return替代break是否合适

34

这是处理C# switch语句的适当方式吗?还是仍然需要明确使用break关键字? 参考

  public static string ToRegistryString(AliceKey.AliceKeyPaths aliceKeyPath)
    {
     switch (aliceKeyPath)
        {
            case AliceKey.AliceKeyPaths.NET_CLR_DATA:
                return @"\.NET CLR Data\";
            case AliceKey.AliceKeyPaths.NET_CLR_NETWORKING:
                return @"\.NET CLR Networking\";
            case AliceKey.AliceKeyPaths.NET_DATA_PROVIDER_MSSQL:
                return @"\.NET Data Provider for SqlServer\";
            case AliceKey.AliceKeyPaths.NET_DATA_PROVIDER_ORACLE:
                return @"\.NET Data Provider for Oracle\";
         }
       return new string(new char[0]);
     }

1
你可以在 Switch 语句之外使用 "return new string(new char[0]);",也可以在所有其他 case 之后使用 "default: return new string(new char[0]);"。这将是一种更清晰的使用 Switch 语句的方式。 - FrozZerrer
2个回答

44

没问题。关键是case块的结尾应该是不可达的 - 在这里你已经返回了。

但你为什么要返回 new string(new char[0]) 而不是 "" 或者 string.Empty 呢?如果你试图确保每次返回的都是一个不同的字符串,那么实际上你将会遇到一个非常奇怪的情况 - 尽管调用了new string(...),但代码实际上总是会返回相同的引用...

最后:我建议将这个switch/case块改成一个Dictionary<AliceKey.AliceKeyPaths, string>

private static readonly Dictionary<AliceKey.AliceKeyPaths, string> RegistryMap =
    new Dictionary<AliceKey.AliceKeyPaths, string>
{
    { 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 : "";
}

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接