Executing Discovered Code with CreateInstance and Invoke

Team Fly 

Page 208

        TextBox1.SelectionLength = 0

    End Sub

End Class

Public Class TestClass

    Private Field1 As String = ''5255"
    Private Field2 As String = "Info goes here"

End Class

Executing Discovered Code with CreateInstance and Invoke

It's well and good to be able to thoroughly examine the types, members, and parameters within an assembly. But reflection has two additional tricks up its sleeve. You can also execute reflected code during runtime (as illustrated by the following example).

In the example in Listing 8.8, you provide the user with a list of methods in a ListBox. The user clicks on that list, and you then ask the user to type in the correct parameters required by the method they chose. Finally, you execute the method.

This illustrates how you can write a program that explores an unknown assembly (unknown at least to you, the programmer, while writing your code). Your program explores the unknown assembly, displays its classes and members during runtime, permits a user to choose among the displayed items, tells them what parameters to pass, and then executes the code from within the reflected classes.

Listing 8.8 ties together several of the techniques introduced throughout in this chapter. Start a new VB.NET project and add a TextBox, a label, a ListBox, and a button. Then type this in:

LISTING 8.8: EXPLORING AN UNKNOWN ASSEMBLY

Imports System.Reflection

    Dim t As Type = GetType(TestClass)
    Dim obj As Object = Activator.CreateInstance(t)
    Dim mInfo As MethodInfo
    Dim l As Integer 'number of parameters
    Dim paramInfo() As ParameterInfo
    Dim cr As String = ControlChars.CrLf

    Private Sub Form1_Load(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles MyBase.Load

Team Fly 


Visual Basic  .NET Power Tools
Visual Basic .NET Power Tools
ISBN: 0782142427
EAN: 2147483647
Year: 2003
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net