121 votos

Características ocultas de VB.NET?

He aprendido un poco la navegación a través de las características ocultas de C # y se sorprendió cuando no pude encontrar algo similar para VB.NET.

¿Cuáles son algunas de sus características ocultas o menos conocidos?

128voto

torial Puntos 9883

El Exception When cláusula es en gran parte desconocido.

Considere esto:

 Public Sub Login(host as string, user as String, password as string, _
                            Optional bRetry as Boolean = False)
Try
   ssh.Connect(host, user, password)
Catch ex as TimeoutException When Not bRetry
   ''//Try again, but only once.
   Login(host, user, password, True)
Catch ex as TimeoutException
   ''//Log exception
End Try
End Sub
 

82voto

Konrad Rudolph Puntos 231505

Personalizada Enums

Una de las ocultos características de VB es el completionlist de documentación XML etiqueta que puede ser utilizado para crear los propios Enum-igual que los tipos con funcionalidad ampliada. Esta característica no funciona en C#, aunque.

Un ejemplo de un reciente código de minas:

'
''' <completionlist cref="RuleTemplates"/>
Public Class Rule
    Private ReadOnly m_Expression As String
    Private ReadOnly m_Options As RegexOptions

    Public Sub New(ByVal expression As String)
        Me.New(expression, RegexOptions.None)
    End Sub

    Public Sub New(ByVal expression As String, ByVal options As RegexOptions)
        m_Expression = expression
        m_options = options
    End Sub

    Public ReadOnly Property Expression() As String
        Get
            Return m_Expression
        End Get
    End Property

    Public ReadOnly Property Options() As RegexOptions
        Get
            Return m_Options
        End Get
    End Property
End Class

Public NotInheritable Class RuleTemplates
    Public Shared ReadOnly Whitespace As New Rule("\s+")
    Public Shared ReadOnly Identifier As New Rule("\w+")
    Public Shared ReadOnly [String] As New Rule("""([^""]|"""")*""")
End Class

Ahora, a la hora de asignar un valor a una variable declarada como Rule, el IDE ofrece una lista de IntelliSense de posibles valores de RuleTemplates.

/EDIT:

Ya que esta es una característica que se basa en el IDE, es difícil mostrar cómo esto se ve cuando se utiliza, pero voy a utilizar una captura de pantalla:

Completion list in action

De hecho, el IntelliSense es 100% idéntico a lo que se obtiene cuando se utiliza un Enum.

49voto

Parsa Puntos 509

¿Ha notado el operador de comparación igual?

Dim b As Boolean = "file.txt" Like "*.txt"

Más de MSDN

 Dim testCheck As Boolean

' The following statement returns True (does "F" satisfy "F"?)'
testCheck = "F" Like "F"

' The following statement returns False for Option Compare Binary'
'    and True for Option Compare Text (does "F" satisfy "f"?)'
testCheck = "F" Like "f"

' The following statement returns False (does "F" satisfy "FFF"?)'
testCheck = "F" Like "FFF"

' The following statement returns True (does "aBBBa" have an "a" at the'
'    beginning, an "a" at the end, and any number of characters in '
'    between?)'
testCheck = "aBBBa" Like "a*a"

' The following statement returns True (does "F" occur in the set of'
'    characters from "A" through "Z"?)'
testCheck = "F" Like "[A-Z]"

' The following statement returns False (does "F" NOT occur in the '
'    set of characters from "A" through "Z"?)'
testCheck = "F" Like "[!A-Z]"

' The following statement returns True (does "a2a" begin and end with'
'    an "a" and have any single-digit number in between?)'
testCheck = "a2a" Like "a#a"

' The following statement returns True (does "aM5b" begin with an "a",'
'    followed by any character from the set "L" through "P", followed'
'    by any single-digit number, and end with any character NOT in'
'    the character set "c" through "e"?)'
testCheck = "aM5b" Like "a[L-P]#[!c-e]"

' The following statement returns True (does "BAT123khg" begin with a'
'    "B", followed by any single character, followed by a "T", and end'
'    with zero or more characters of any type?)'
testCheck = "BAT123khg" Like "B?T*"

' The following statement returns False (does "CAT123khg" begin with'
'    a "B", followed by any single character, followed by a "T", and'
'    end with zero or more characters of any type?)'
testCheck = "CAT123khg" Like "B?T*"
 

48voto

Konrad Rudolph Puntos 231505

Typedefs

VB conoce una especie primitiva de typedef a través de Import alias:

 Imports S = System.String

Dim x As S = "Hello"
 

Esto es más útil cuando se utiliza junto con los tipos genéricos:

 Imports StringPair = System.Collections.Generic.KeyValuePair(Of String, String)
 

45voto

Nescio Puntos 12613

Oh! y no se olvide de los literales XML .

 Dim contact2 = _
        <contact>
          <name>Patrick Hines</name>
          <%= From p In phoneNumbers2 _
            Select <phone type=<%= p.Type %>><%= p.Number %></phone> _
          %>
        </contact>
 

Iteramos.com

Iteramos es una comunidad de desarrolladores que busca expandir el conocimiento de la programación mas allá del inglés.
Tenemos una gran cantidad de contenido, y también puedes hacer tus propias preguntas o resolver las de los demás.

Powered by:

X