Listing 1
Public Class Car
Public Sub Brake()
' Implement car-oriented braking here
End Sub
End Class
Public Class Truck
Public Sub Brake()
' Implement truck-oriented braking here
End Sub
End Class
Listing 2
Interface Vehicle
Sub Brake()
End Interface
Public Class Car
Implements Vehicle
Public Sub Brake() Implements Vehicle.Brake
' Implement car-oriented braking here
End Sub
End Class
Public Class Truck
Implements Vehicle
Public Sub Brake() Implements Vehicle.Brake
' Implement truck-oriented braking here
End Sub
End Class
Listing 3
Public Function CreateObjectFromAssembly( _
ByVal AssemblyFileName As String, _
ByVal TypeName As String) As Object
Dim asm As [Assembly]
Dim CurrentDomain As AppDomain = Nothing
Dim StartupPath As String
Dim ObjectPath As String
Try
' reference the current
' Application Domain
CurrentDomain = AppDomain.CurrentDomain
' get the fully-qualified name of the
' executing assembly, as a url
ObjectPath = [Assembly].GetExecutingAssembly()_.GetName().CodeBase
' remove the domain from the front
ObjectPath = ObjectPath.Replace("file:///","")
' extract just the path
StartupPath = Path.GetDirectoryName(ObjectPath)
' load the assembly
asm = [Assembly].LoadFrom( _
String.Format("{0}\\{1}", _
StartupPath, _
AssemblyFileName))
' create the object
Return CurrentDomain.CreateInstanceAndUnwrap( _
asm.FullName, _
TypeName)
Catch ex As Exception
' handle errors here
End Try
End Function
Listing 4
Public Function GetMethodFromInterface( _
ByVal AssemblyFile As String, _
ByVal InterfaceName As String) _
As Type
Dim asm As [Assembly]
Dim ClassToInstantiate As Type = Nothing
' load the assembly
asm = [Assembly].LoadFile(AssemblyFile)
' loop through all the types in the assembly
For Each t As Type In asm.GetTypes
' get a list of the interfaces implemented
' by the type. the list is filtered by the
' passed-in interface name
Dim Interfaces As Type() = t.FindInterfaces( _
New TypeFilter(AddressOf InterfaceFilter), _
InterfaceName)
' any found?
If Interfaces.Length > 0 Then
' return the type
ClassToInstantiate = t
Exit For
End If
Next
Return ClassToInstantiate
End Function
Public Shared Function InterfaceFilter( _
ByVal TypeObject As Type, _
ByVal CriteriaObject As Object) _
As Boolean
' compare interface names
If TypeObject.ToString = _
CriteriaObject.ToString Then
Return True
Else
Return False
End If
End Function