構造体のストラクチャーについて説明します。
通常のクラスとの違いは通常のクラスが参照型であるのに対し、構造体が値型であることです。
ストラクチャーを定義するには
<属性> Structure <構造体名> <属性> <メンバー名> As <変数型名> : End Structure
ストラクチャー例
Public Structure Person
Implements IDisposable
Private m_Name As String
Private m_Age As Integer
'Newで初期化された場合用のコンストラクタ
Sub New(ByVal name As String, ByVal age As Integer)
Me.m_Name = name
Me.m_Age = age
End Sub
'IDisposableインターフェースの実装デストラクタ
Public Sub Dispose() Implements System.IDisposable.Dispose
Console.WriteLine("Disposeが呼び出された。")
End Sub
'名前を設定する
Public Sub SetName(ByVal name As String)
Me.m_Name = name
End Sub
'名前を取得する
Public Function GetName() As String
Return (Me.m_Name)
End Function
'年齢を設定する
Public Property Age() As Integer
Get
Return m_Age
End Get
Set(ByVal value As Integer)
m_Age = value
End Set
End Property
End Structure
通常のクラスの使い方とあまり変わりません。通常では、ストラクチャーを使うことはあまりないと思います。
固定長の配列として扱いたい場合などに使用します。
固定長で宣言する
StructLayoutを使用するためImports System, System.Runtime.InteropServicesを追加します。
必ずしもStructLayoutの設定はいらないのですが、メモリの確保の仕方が32bit,64bitなどの機械(OS)により異なります。
ので以下はバイト単位でメモリを確保したいので指定します。(通常ではバイト単位で連続に確保されない)
Imports System, System.Runtime.InteropServices
<StructLayout(LayoutKind.Sequential, Pack:=1)>
Friend Structure Person
<VBFixedArray(20 - 1)> Public Name() As Byte
<VBFixedArray(2 - 1)> Public Age() As Byte
End Structure
LayoutKind列挙体は、アンマネージ コードにエクスポートするときにオブジェクトのレイアウトを制御します。