Вопрос по vb.net – Скрытые возможности VB.NET?

121

Я научился немного просматриватьСкрытые возможности из C # и был удивлен, когда я не смог найти что-то похоже на VB.NET.

Так каковы некоторые из его скрытых или менее известных особенностей?

Ваш Ответ

30   ответов
14

Import winf = System.Windows.Forms

''Later
Dim x as winf.Form
Error: User Rate Limit Exceededstackoverflow.com/questions/92869/…
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededenhancesError: User Rate Limit Exceeded
39

Dim x as New MyClass With {.Prop1 = foo, .Prop2 = bar}
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
9

StrConv(stringToTitleCase, VbStrConv.ProperCase,0) ''0 is localeID
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
37
If conditional and coalesce operator

t know how hidden you'd call it, but the Iif([expression],[value if true],[value if false]) As Object function could count.

Error: User Rate Limit ExceededdeprecatedError: User Rate Limit ExceededIfError: User Rate Limit Exceeded

Dim x = If(a = b, c, d)

Dim hello As String = Nothing
Dim y = If(hello, "World")

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededIf()Error: User Rate Limit ExceededIIf()

Dim x = If(b<>0,a/b,0)
Error: User Rate Limit Exceeded Sean Gough
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededcompletely equivalentError: User Rate Limit Exceeded:?Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
25

Static members in methods.

Error: User Rate Limit Exceeded

Function CleanString(byval input As String) As String
    Static pattern As New RegEx("...")

    return pattern.Replace(input, "")
End Function

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Function GetNextRandom() As Integer
    Static r As New Random(getSeed())

    Return r.Next()
End Function 

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
16

Sub MyFunc(Optional msg as String= "", Optional displayOrder As integer = 0)

    'Do stuff

End function

Module Module1

    Sub Main()

        MyFunc() 'No params specified

    End Sub

End Module

MyFunc(displayOrder:=10, msg:="mystring")
Error: User Rate Limit ExceededmixError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededveryError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
17

Forcing ByVal

Error: User Rate Limit Exceeded

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim R = 4
    Trace.WriteLine(R)
    Test(R)
    Trace.WriteLine(R)
    Test((R))
    Trace.WriteLine(R)
End Sub
Private Sub Test(ByRef i As Integer)
    i += 1
End Sub

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
12

Dim x As New Something : x.CallAMethod
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededCall (New Something).CallAMethod()
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
11

Optional Parameters

Error: User Rate Limit Exceeded

Function CloseTheSystem(Optional ByVal msg AS String = "Shutting down the system...")
   Console.Writeline(msg)
   ''//do stuff
End Function
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededonlyError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededyoooder.com/wordpress/?p=62
32

Select Case Role
  Case "Admin"
         ''//Do X
  Case "Tester"
         ''//Do Y
  Case "Developer"
         ''//Do Z
  Case Else
       ''//Exception case
End Select

Select Case Amount
 Case Is < 0
    ''//What!!
 Case 0 To 15
   Shipping = 2.0
 Case 16 To 59
    Shipping = 5.87
 Case Is > 59
    Shipping = 12.50
 Case Else
    Shipping = 9.99
 End Select

Select Case True
 Case a = b
    ''//Do X
 Case a = c
    ''//Do Y
 Case b = c
    ''//Do Z
 Case Else
   ''//Exception case
 End Select
Error: User Rate Limit ExceededSelect Case TrueError: User Rate Limit ExceededlooksError: User Rate Limit ExceededeachError: User Rate Limit ExceededCaseError: User Rate Limit ExceededfirstError: User Rate Limit ExceededIfError: User Rate Limit ExceededIf...Else If...Else If...Else).
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
9

Properties with parameters

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Private Shared m_Dictionary As IDictionary(Of String, Object) = _
             New Dictionary(Of String, Object)

Public Shared Property DictionaryElement(ByVal Key As String) As Object
    Get
        If m_Dictionary.ContainsKey(Key) Then
            Return m_Dictionary(Key)
        Else
            Return [String].Empty
        End If
    End Get
    Set(ByVal value As Object)
        If m_Dictionary.ContainsKey(Key) Then
            m_Dictionary(Key) = value
        Else
            m_Dictionary.Add(Key, value)
        End If

    End Set
End Property
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
45

XML-литералы.

Dim contact2 = _
        <contact>
          <name>Patrick Hines</name>
          <%= From p In phoneNumbers2 _
            Select <phone type=<%= p.Type %>><%= p.Number %></phone> _
          %>
        </contact>
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededswortham.blogspot.com/2009/03/vb-2008.html
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded<string>This string contains "quotes" and it's OK.</string>.ValueError: User Rate Limit ExceedednotError: User Rate Limit Exceeded
128

Exception When пункт в значительной степени неизвестен.

Учти это:

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
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededblogs.msdn.com/clrteam/archive/2009/02/05/…
Error: User Rate Limit Exceeded
38
DirectCast

DirectCastError: User Rate Limit ExceededCTypeError: User Rate Limit ExceededCTypeфактическое поведение, следовательно, часто непрозрачно, и совершенно не очевидно, какой тип преобразования выполняется.

DirectCastError: User Rate Limit Exceeded

Unboxing of a value type, and upcasting in the class hierarchy.

Любой другой актерский состав не будет работать (например, попытка распаковатьIntegerError: User Rate Limit ExceededDoubleError: User Rate Limit ExceededDirectCastError: User Rate Limit Exceeded

Error: User Rate Limit ExceededCTypeError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded1Error: User Rate Limit ExceededDirectCastError: User Rate Limit ExceededWhenever possible, favour DirectCast over the more general CType operator.Error: User Rate Limit ExceededCTypeError: User Rate Limit ExceededCTypeError: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

1)Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

In the real world, you're hardly ever going to notice the difference, so you might as well go with the more flexible conversion operators like CType, CInt, etc.

Error: User Rate Limit ExceededError: User Rate Limit Exceeded)

Error: User Rate Limit ExceededTryCastError: User Rate Limit ExceededCType.
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededTryCastError: User Rate Limit Exceeded
Error: User Rate Limit ExceededalwaysError: User Rate Limit ExceededcouldError: User Rate Limit ExceededalwaysError: User Rate Limit Exceeded
21

The technical name for the ! operator is the "dictionary lookup operator." A dictionary is any collection type that is indexed by a key rather than a number, just like the way that the entries in an English dictionary are indexed by the word you want the definition of. The most common example of a dictionary type is the System.Collections.Hashtable, which allows you to add (key, value) pairs into the hashtable and then retrieve values using the keys. For example, the following code adds three entries to a hashtable, and looks one of them up using the key "Pork".

Dim Table As Hashtable = New Hashtable
Table("Orange") = "A fruit"
Table("Broccoli") = "A vegetable"
Table("Pork") = "A meat" 
Console.WriteLine(Table("Pork"))

The ! operator can be used to look up values from any dictionary type that indexes its values using strings. The identifier after the ! is used as the key in the lookup operation. So the above code could instead have been written:

Dim Table As Hashtable = New Hashtable
Table!Orange = "A fruit"
Table!Broccoli = "A vegetable"
Table!Pork = "A meat"
Console.WriteLine(Table!Pork)

The second example is completely equivalent to the first, but just looks a lot nicer, at least to my eyes. I find that there are a lot of places where ! can be used, especially when it comes to XML and the web, where there are just tons of collections that are indexed by string. One unfortunate limitation is that the thing following the ! still has to be a valid identifier, so if the string you want to use as a key has some invalid identifier character in it, you can't use the ! operator. (You can't, for example, say "Table!AB$CD = 5" because $ isn't legal in identifiers.) In VB6 and before, you could use brackets to escape invalid identifiers (i.e. "Table![AB$CD]"), but when we started using brackets to escape keywords, we lost the ability to do that. In most cases, however, this isn't too much of a limitation.

To get really technical, x!y works if x has a default property that takes a String or Object as a parameter. In that case, x!y is changed into x.DefaultProperty("y"). An interesting side note is that there is a special rule in the lexical grammar of the language to make this all work. The ! character is also used as a type character in the language, and type characters are eaten before operators. So without a special rule, x!y would be scanned as "x! y" instead of "x ! y". Fortunately, since there is no place in the language where two identifiers in a row are valid, we just introduced the rule that if the next character after the ! is the start of an identifier, we consider the ! to be an operator and not a type character.

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededforgetting again right.... NOW
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
14

Public Event SomethingHappened As EventHandler

if(SomethingHappened != null)
{
  ...
}

If Not SomethingHappenedEvent Is Nothing OrElse SomethingHappenedEvent.GetInvocationList.Length = 0 Then
...
End If

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
49

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

Больше от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*"
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
25

/ являетсяDouble
\Integer

Sub Main()
    Dim x = 9 / 5  
    Dim y = 9 \ 5  
    Console.WriteLine("item x of '{0}' equals to {1}", x.GetType.FullName, x)
    Console.WriteLine("item y of '{0}' equals to {1}", y.GetType.FullName, y)

    'Results:
    'item x of 'System.Double' equals to 1.8
    'item y of 'System.Int32' equals to 1
End Sub
Error: User Rate Limit Exceeded
12

Dim independanceDay As DateTime = #7/4/1776#

Dim independanceDay = #7/4/1776#

Dim independanceDay as DateTime = New DateTime(1776, 7, 4)
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededreallyError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
26
AndAlso/OrElse logical operators

)

Error: User Rate Limit Exceeded
31

Microsoft.VisualBasic.FileIO.TextFieldParser

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
23

"My" NamespaceMy

My.Computer: Access to information related to the computer such as file system, network, devices, system information, etc. It provides access to a number of very important resources including My.Computer.Network, My.Computer.FileSystem, and My.Computer.Printers. My.Application: Access to information related to the particular application such as name, version, current directory, etc. My.User: Access to information related to the current authenticated user. My.Resources: Access to resources used by the application residing in resource files in a strongly typed manner. My.Settings: Access to configuration settings of the application in a strongly typed manner.
Error: User Rate Limit Exceededsecretgeek.net/refactvb.asp
Error: User Rate Limit Exceededurbandictionary.com/define.php?term=ftw
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
13

Dim myString = _
    "This string contains ""quotes"" and they're ugly."

Dim myString = _
    <string>This string contains "quotes" and they're nice.</string>.Value

Dim csvTestYuck = _
    """Smith"", ""Bob"", ""123 Anywhere St"", ""Los Angeles"", ""CA"""

Dim csvTestMuchBetter = _
    <string>"Smith", "Bob", "123 Anywhere St", "Los Angeles", "CA"</string>.Value

<string>

Error: User Rate Limit Exceeded
<q>Error: User Rate Limit Exceeded
82
Custom Enums

hidden Особенности VB являетсяcompletionlist Тег XML документации, который можно использовать для создания собственногоEnum-подобные типы с расширенной функциональностью. Однако эта функция не работает в C #.

Один пример из моего недавнего кода:

'
''' <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

Теперь при присвоении значения переменной, объявленной какRuleError: User Rate Limit ExceededRuleTemplates.

/EDIT:

Поскольку эта функция основана на среде IDE, трудно показать, как она выглядит, когда вы ее используете, но я просто буду использовать снимок экрана:

Error: User Rate Limit Exceeded

На самом деле IntelliSense на 100% идентичен тому, что вы получаете при использованииEnum.

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededfriendError: User Rate Limit ExceededRuleError: User Rate Limit ExceededRuleTemplate.
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
23
Custom Events

Public Class ApplePie
    Private ReadOnly m_BakedEvent As New List(Of EventHandler)()

    Custom Event Baked As EventHandler
        AddHandler(ByVal value As EventHandler)
            Console.WriteLine("Adding a new subscriber: {0}", value.Method)
            m_BakedEvent.Add(value)
        End AddHandler

        RemoveHandler(ByVal value As EventHandler)
            Console.WriteLine("Removing subscriber: {0}", value.Method)
            m_BakedEvent.Remove(value)
        End RemoveHandler

        RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
            Console.WriteLine("{0} is raising an event.", sender)
            For Each ev In m_BakedEvent
                ev.Invoke(sender, e)
            Next
        End RaiseEvent
    End Event

    Public Sub Bake()
        ''// 1. Add ingredients
        ''// 2. Stir
        ''// 3. Put into oven (heated, not pre-heated!)
        ''// 4. Bake
        RaiseEvent Baked(Me, EventArgs.Empty)
        ''// 5. Digest
    End Sub
End Class

Module Module1
    Public Sub Foo(ByVal sender As Object, ByVal e As EventArgs)
        Console.WriteLine("Hmm, freshly baked apple pie.")
    End Sub

    Sub Main()
        Dim pie As New ApplePie()
        AddHandler pie.Baked, AddressOf Foo
        pie.Bake()
        RemoveHandler pie.Baked, AddressOf Foo
    End Sub
End Module
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededmsdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx
19

Public Sub GetISCSIAdmInfo(ByRef xDoc As System.Xml.XmlDocument) Implements IUnix.GetISCSIInfo

End Sub
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
14

Class CodeException
Public [Error] as String
''...
End Class

''later
Dim e as new CodeException
e.Error = "Invalid Syntax"

Class Timer
Public Sub Start()
''...
End Sub

Public Sub [Stop]()
''...
End Sub
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded Sean Gough
48
Typedefs

typedef с помощьюImport псевдонимы:

Imports S = System.String

Dim x As S = "Hello"

Это более полезно при использовании в сочетании с универсальными типами:

Imports StringPair = System.Collections.Generic.KeyValuePair(Of String, String)
Error: User Rate Limit ExceededImports Assert = xUnit.Assert
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededreadError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
ImportsError: User Rate Limit Exceeded
31

With

With ReallyLongClassName
    .Property1 = Value1
    .Property2 = Value2
    ...
End With

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
15

Using lockThis as New MyLocker(objToLock)

End Using
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

Похожие вопросы