リフレクション


VB.NETでのReflectionクラスを使用したサンプル

Imports System.Reflection
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'フォルダ内のDLLを取得
        Call getDllList()

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'リフレクション
        Call subReflection(cboDll.SelectedItem)

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'DLLの実行
        Call subExecute(cboDll.SelectedItem)

    End Sub

    '
    '   カレントディレクトリにあるDLLをコンボボックスに出力する
    '
    Private Function getDllList() As Boolean
        Dim sFolder As String
        Dim sFile As String

        'カレントディレクトリを取得
        sFolder = Environment.CurrentDirectory

        If Directory.Exists(sFolder) = False Then
            Return True
        End If

        'フォルダ内にあるDLLを検索
        For Each sFile In Directory.GetFiles(sFolder, "*.dll")

            cboDll.Items.Add(sFile)

        Next

        Return True
    End Function

    '
    '  DLLのメソッド、プロパティをコンボボックスに出力する
    '
    Private Function subReflection(ByVal dllPath As String) As Boolean
        Dim oDllAssembly As Assembly
        Dim oDllModule As Type
        Dim oMethod As MethodInfo
        Dim oMethods() As MethodInfo
        Dim oProp As PropertyInfo
        Dim oProps() As PropertyInfo

        Try
            ' ファイルの存在チェック
            If File.Exists(dllPath) = False Then
                Return False
            End If

            ' DLLをロード
            oDllAssembly = Assembly.LoadFile(dllPath)
            oDllModule = oDllAssembly.GetExportedTypes(0)

            ' メソッドのコレクションを取得
            oMethods = oDllModule.GetMethods()

            For Each oMethod In oMethods
                cboMethod.Items.Add(oMethod.Name)
            Next


            ' プロパティのコレクションを取得
            oProps = oDllModule.GetProperties

            For Each oProp In oProps
                cboProp.Items.Add(oProp.Name)
            Next

            Return True

        Catch ex As Exception

            Return False
        End Try
    End Function

    '
    '   DLLのメソッドを呼び出す
    '
    Private Sub subExecute(ByVal dllPath As String)
        Dim oDllAssembly As Assembly
        Dim oDll As Object

        'DLLのロード
        oDllAssembly = Assembly.LoadFile(dllPath)
        oDll = oDllAssembly.CreateInstance(oDllAssembly.GetExportedTypes(0).FullName)

        'ロードしたDLLのメソッドを実行
        MsgBox(oDll.GetType.FullName)

    End Sub

End Class