Back to Top

プログラムの覚書

Author Archives: miyunsarna

VB.NETキャスト

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

 

 

VB.NET配列文

配列の確保割り当てには複数のやり方があります。

方法1
Dim 変数名(要素数) As 型名

方法2
Dim 変数名() As 型名 = {値1 [, 値2...]}

方法3
Dim 変数名() As 型名
変数名 = New 型名(要素数){}

方法4
Dim 変数名() As 型名
変数名 = New 型名(要素数){値1 [, 値2...]}
'方法1

'配列を確保する
Dim arr1(5) As Integer

-------------------------------------------------------
'方法2

'配列を確保し値を割り当てる
Dim arr2() As Integer = {100, 200, 300, 400, 500}

-------------------------------------------------------
'方法3

'参照型の配列変数のみ確保する
Dim arr3() As Integer

'配列の実体を確保し割り当てる
arr3 = New Integer(4){}

-------------------------------------------------------
'方法4

'参照型の配列変数のみ確保する
Dim arr4() As Integer

'配列に値を割り当てる
arr4 = New Integer(){ 1, 2, 3, 4, 5 }