VB.NET Cambiar Declaración GoTo Caso


Estoy escribiendo algún código en VB.NET eso usa una sentencia switch pero en uno de los casos necesita saltar a otro bloque. En C# se vería así:

switch (parameter)
{
    case "userID":
        // does something here.
    case "packageID":
        // does something here.
    case "mvrType":
        if (otherFactor)
        {
            // does something here.
        }
        else
        {
            goto default;
        }
    default:
        // does some processing...
        break;
}

Sin embargo, no se como convertir esto a VB.NET. He intentado esto:

Select Case parameter 
    Case "userID"
        ' does something here.
    Case "packageID"
        ' does something here.
    Case "mvrType" 
        If otherFactor Then 
            ' does something here. 
        Else 
            GoTo Case Else 
        End If 
    Case Else 
        ' does some processing... 
        Exit Select 
End Select     

Pero cuando hago esto obtengo un error del compilador: "Identificador esperado". Hay una línea ondulada bajo "Caso". Alguna idea?

Además, ¿es incorrecto usar una declaración GoTo en este caso? Parece que de otra manera tendría que volver a escribir se.


He cambiado mi código a lo siguiente:

If otherFactor AndAlso parameter = "mvrType" Then 
    'does something here 
Else 
    ' My original "Select Case statement" here without the case for "mvrType" 
End If
Author: Drakonoved, 2009-05-04

9 answers

No hay equivalente en VB.NET que pude encontrar. Para este fragmento de código, probablemente querrá abrirlo en Reflector y cambiar el tipo de salida a VB para obtener la copia exacta del código que necesita. Por ejemplo, cuando pongo lo siguiente en el Reflector:

switch (args[0])
{
    case "UserID":
        Console.Write("UserID");
        break;
    case "PackageID":
        Console.Write("PackageID");
        break;
    case "MVRType":
        if (args[1] == "None")
            Console.Write("None");
        else
            goto default;
        break;
    default:
        Console.Write("Default");
        break;
}

Me dio lo siguiente VB.NET salida.

Dim CS$4$0000 As String = args(0)
If (Not CS$4$0000 Is Nothing) Then
    If (CS$4$0000 = "UserID") Then
        Console.Write("UserID")
        Return
    End If
    If (CS$4$0000 = "PackageID") Then
        Console.Write("PackageID")
        Return
    End If
    If ((CS$4$0000 = "MVRType") AndAlso (args(1) = "None")) Then
        Console.Write("None")
        Return
    End If
End If
Console.Write("Default")

Como puede ver, puede lograr la misma instrucción switch case con las instrucciones If. Por lo general, no recomiendo esto porque hace que sea más difícil entender, pero VB.NET no parece admitir la misma funcionalidad, y usar Reflector podría ser la mejor manera de obtener el código que necesita para que funcione sin mucho dolor.

Actualización:

Acaba de confirmar que no puede hacer exactamente lo mismo en VB.NET, pero apoya algunas otras cosas útiles. Parece que la conversión de la declaración IF es tu mejor opción, o tal vez alguna refactorización. Aquí está la definición para Seleccionar...Caso

Http://msdn.microsoft.com/en-us/library/cy37t14y.aspx

 13
Author: Nick Berardi,
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
2009-05-04 13:58:02

¿por Qué no hacerlo así:

Select Case parameter     
   Case "userID"                
      ' does something here.        
   Case "packageID"                
      ' does something here.        
   Case "mvrType"                 
      If otherFactor Then                         
         ' does something here.                 
      Else                         
         ' do processing originally part of GoTo here
         Exit Select  
      End If      
End Select

No estoy seguro de si no tener un caso más al final es un gran problema o no, pero parece que realmente no necesita el ir a si solo lo pone en la declaración else de su si.

 20
Author: ryanulit,
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
2009-05-04 13:42:16

¿Por qué no refactorizas el caso predeterminado como método y lo llamas desde ambos lugares? Esto debería ser más legible y le permitirá cambiar el código de una manera más eficiente.

 11
Author: Nicolas Irisarri,
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
2009-05-04 14:02:58

No estoy seguro de que sea una buena idea usar un GoTo, pero si quieres usarlo, puedes hacer algo como esto:

Select Case parameter 
    Case "userID"
        ' does something here.
    Case "packageID"
        ' does something here.
    Case "mvrType" 
        If otherFactor Then 
            ' does something here. 
        Else 
            GoTo caseElse
        End If 
    Case Else
caseElse:
        ' does some processing... 
End Select

Como he dicho, aunque funciona, GoTo no es una buena práctica, así que aquí hay algunas soluciones alternativas:

Usando elseif...

If parameter = "userID" Then
    ' does something here.
ElseIf parameter = "packageID" Then
    ' does something here.
ElseIf parameter = "mvrType" AndAlso otherFactor Then
    ' does something here.
Else
    'does some processing...
End If

Usando un valor booleano...

Dim doSomething As Boolean

Select Case parameter
Case "userID"
     ' does something here.
Case "packageID"
     ' does something here.
Case "mvrType"
     If otherFactor Then
          ' does something here. 
     Else
          doSomething = True
     End If
Case Else
     doSomething = True
End Select

If doSomething Then
     ' does some processing... 
End If

En lugar de establecer una variable booleana, también podría llamar a un método directamente en ambos casos...

 4
Author: Meta-Knight,
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
2012-05-25 12:42:59

En VB.NET, puede aplicar varias condiciones incluso si las otras condiciones no se aplican al parámetro Select. Véase a continuación:

Select Case parameter 
    Case "userID"
                ' does something here.
        Case "packageID"
                ' does something here.
        Case "mvrType" And otherFactor
                ' does something here. 
        Case Else 
                ' does some processing... 
End Select
 3
Author: Zachafer,
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
2012-06-26 21:34:47

Primero debe declarar label usa esto:

    Select Case parameter 
        Case "userID"
                    ' does something here.
            Case "packageID"
                    ' does something here.
            Case "mvrType" 
                    If otherFactor Then 
                            ' does something here. 
                    Else 
                            GoTo else
                    End If 

            Case Else 
else :
                    ' does some processing... 
                    Exit Select 
    End Select
 2
Author: Sadegh,
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
2009-05-04 13:45:28
Select Case parameter 
    ' does something here. 
    ' does something here. 
    Case "userID", "packageID", "mvrType" 
        If otherFactor Then 
            ' does something here. 
        Else 
            goto case default 
        End If 
    Case Else 
        ' does some processing... 
        Exit Select 
End Select
 1
Author: DanM7,
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
2015-05-26 15:07:37
Select Case parameter
    ' does something here.
    ' does something here.
    Case "userID", "packageID", "mvrType"
                ' does something here.
        If otherFactor Then
        Else
            goto case default
        End If
    Case Else
        ' does some processing...
        Exit Select
End Select
 -1
Author: Taran,
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
2012-08-29 09:41:30
Select Case parameter 
    Case "userID"
        ' does something here.
    Case "packageID"
        ' does something here.
    Case "mvrType" 
        If otherFactor Then 
            ' does something here.
        End If 
    Case Else 
        ' does some processing... 
        Exit Select 
End Select

Hay una razón para el goto? Si no cumple con el criterio if, simplemente no realizará la función e irá al siguiente caso.

 -1
Author: Jason Zielke,
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
2015-08-13 02:22:52