|
|
Title | List and create instances of the types defined in an assembly in VB .NET |
Description | This example shows how to list and create instances of the types defined in an assembly in VB .NET. |
Keywords | assembly, type, data type, reflection, invoke, VB .NET |
Categories | VB.NET |
|
|
This example shows how to learn about the types defined in an assembly and create instances of them at run time.
Before you run the main program, load the project Classes and compile it. This project creates a DLL that defines the Person, Employee, Manager, and Customer classes.
After you build the DLL, run the main program. Enter the compiled dll's location or browse for it and click the Go button. The program uses the location you entered to create an Assembly object. It clears its ListBox and fills the list with the type names it gets from the Assembly's GetTypes method.
Note that the code must include the type Assembly in square brackets because "Assembly" is also a keyword.
|
|
Private Sub btnGo_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnGo.Click
Me.Cursor = Cursors.WaitCursor
Application.DoEvents()
Dim assem As [Assembly] = _
[Assembly].LoadFrom(txtPath.Text)
lstTypes.Items.Clear()
For Each defined_type As System.Type In assem.GetTypes()
lstTypes.Items.Add(defined_type)
Next defined_type
lstTypes.Enabled = True
Me.Cursor = Cursors.Default
End Sub
|
|
If you select a type from the list and click the Create button, the program retrieves the System.Type object associated with that item. It calls the Type's GetConstructor method to get a ConstructorInfo object describing an empty constructor. It then calls the ConstructorInfo object's Invoke method to create an instance of the type. The program finishes by invoking the newly created object's ToString method and displaying the results.
|
|
Private Sub btnCreate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCreate.Click
' Get info for an empty constructor for the type.
Dim selected_type As System.Type = _
lstTypes.SelectedItem()
Dim constructor_info As ConstructorInfo
constructor_info = _
selected_type.GetConstructor(System.Type.EmptyTypes)
' Invoke the constructor.
Dim obj As Object = constructor_info.Invoke(Nothing)
' Display the results of the object's ToString method.
MessageBox.Show("Created " & TypeName(obj) & " " & _
obj.ToString())
End Sub
|
|
|
|
|
|