VBは暗黙的なデータ型変換が通常行われます。またキャストにはいろいろな方法があります。

Option Strict StatementをONにすることにより、それを制限することができます。

1.[プロジェクト] メニューの [プロパティ] をクリックします

2.[コンパイル] タブで、[Option Strict] ボックスの値をONに設定します。

暗黙的なデータ型変換を拡大変換だけに制限し、遅延バインディングを禁止し、Object 型になる暗黙の型指定を禁止します。

Convertによるキャスト

Dim f As Single = 100.5
Dim i As Integer = Convert.ToInt32(f)

CInt()等によるキャスト

 Dim f As Single = 1.5F
 Dim i As Integer = CInt(f)

CType()によるキャスト

'Single型をInteger型に変換
Dim f As Single = 1.5F
Dim i1 As Integer = CType(f, Integer)

'Long型をInteger型に変換する 
Dim l As Long = 100
Dim i2 As Integer = CType(l, Integer)

'参照変換 
Dim btn As New System.Windows.Forms.Button()
Dim ctl As System.Windows.Forms.Control = CType(btn, System.Windows.Forms.Control)

'変換演算子による変換 
Dim pnt As System.Drawing.Point = New Point(0, 0)
Dim siz As System.Drawing.Size = CType(pnt, System.Drawing.Size)

TryCast()によるキャスト

Dim lbl As New System.Windows.Forms.Label()
Dim ctl As System.Windows.Forms.Control = TryCast(lbl, System.Windows.Forms.Control)

DirectCast()によるキャスト

Dim lbl As New System.Windows.Forms.Label()
Dim ctl As System.Windows.Forms.Control = DirectCast(lbl, System.Windows.Forms.Control)

 

キャストできるか調べる

Dim lbl As New System.Windows.Forms.Label()

If TypeOf lbl Is System.Windows.Forms.Control Then
    Dim ctl1 As System.Windows.Forms.Control = CType(lbl, System.Windows.Forms.Control)
End If


Dim ctl2 As System.Windows.Forms.Control = TryCast(lbl, System.Windows.Forms.Control)
If ctl2 IsNot Nothing Then
    MessageBox.Show("キャストに成功")
End If