Casting in visual basic?

前端 未结 5 1551
情书的邮戳
情书的邮戳 2020-12-16 16:26

I\'m a C# programmer who is forced to use VB (eh!!!!). I want to check multiple controls state in one method, in C# this would be accomplished like so:

if ((         


        
相关标签:
5条回答
  • 2020-12-16 16:50

    C#:

    (CheckBox)sender
    

    VB:

    CType(sender, CheckBox)
    
    0 讨论(0)
  • 2020-12-16 17:04

    VB actually has 2 notions of casting.

    1. CLR style casting
    2. Lexical Casting

    CLR style casting is what a C# user is more familiar with. This uses the CLR type system and conversions in order to perform the cast. VB has DirectCast and TryCast equivalent to the C# cast and as operator respectively.

    Lexical casts in VB do extra work in addition to the CLR type system. They actually represent a superset of potential casts. Lexical casts are easily spotted by looking for the C prefix on the cast operator: CType, CInt, CString, etc ... These cast, if not directly known by the compiler, will go through the VB run time. The run time will do interpretation on top of the type system to allow casts like the following to work

    Dim v1 = CType("1", Integer)
    Dim v2 = CBool("1")
    
    0 讨论(0)
  • 2020-12-16 17:06

    DirectCast will perform the conversion at compile time but can only be used to cast reference types. Ctype will perform the conversion at run time (slower than converting at compile time) but is obviously useful for convertng value types. In your case "sender" is a reference type so DirectCast would be the way to go.

    0 讨论(0)
  • 2020-12-16 17:10

    Casting in VB.net uses the keyword ctype. So the C# statement (CheckBox)sender is equivalent to ctype(sender,CheckBox) in VB.net.

    Therefore your code in VB.net is:

    if ctype(sender,CheckBox).Checked =True Then
        ' Do something...
    else
        ' Do something else...
    End If
    
    0 讨论(0)
  • 2020-12-16 17:12

    Adam Robinson is correct, also DirectCast is available to you.

    0 讨论(0)
提交回复
热议问题