la instrucción del interruptor de c# es vuelta conveniente para substituir la rotura


¿Es esta una forma apropiada de manejar instrucciones de cambio de c# o todavía se requiere una interrupción explícita? referencia

  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]);
     }
Author: Community, 2010-07-07

2 answers

Eso está bien. El punto es que el final de un bloque de caso debe ser inalcanzable - que está aquí, porque has regresado.

¿Por qué regresas new string(new char[0]) en lugar de solo "" o string.Empty? Si usted está tratando de asegurarse de que es una cadena diferente cada vez, en realidad se encontrará con un caso de esquina muy extraño-a pesar de llamar new string(...) ese código siempre devolverá la misma referencia...

Finalmente: Realmente sugeriría cambiar este bloque switch / case en solo un 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 : "";
}
 40
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-07 15:19:24

No necesita usar específicamente una instrucción break solo una que cambie el flujo de control, por lo que una goto o una return debería funcionar.

Ver MSDN para más información: http://msdn.microsoft.com/en-us/library/06tc147t (VS.71).aspx

 5
Author: Jordan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-07 15:21:55