Well, the most likely reason is the namespace reference. Look at the
GetCommand function...
Function GetCommand() As String
Return String.Format( _
"ConsoleApplication39.Module1+{0}", _
CommandNames(rand.Next(0, CommandNames.Length)))
End Function
See how I'm forming the object name? Most likely, unless you named the
application ConsoleApplication39 then you are going to get that error
If everything else is the same, then chang the ConsoleApplication39 part of
that to the name of your app. This is not how I would do this in production
code though... This was only meant as a simple example
Just to make this a little more clear - here is more along the lines of what I
would do (because sometimes I've had these in separate assemblies, etc.). I
put the full names of the types in a dictionary and then create them that
way... Again, here is the simple example, without a hardcoded namespace...
Option Strict On
Option Explicit On
Imports System
Imports System.Reflection
Module Module1
Private _commandNames() As String = New String() {"Sub_1", "Sub_2", "Sub_3"}
Private _typeLookup As New Dictionary(Of String, String)()
Private _rand As New Random()
Sub Main()
' init lookup stuff for example
Dim types() As Type = Assembly.GetExecutingAssembly().GetTypes()
For Each t As Type In types
If t.BaseType.Equals(GetType(BaseCommand)) Then
_typeLookup.Add(t.Name, t.FullName)
End If
Next
For i = 1 To 20
Dim command As BaseCommand = _
DirectCast(Assembly.GetExecutingAssembly().CreateInstance(GetCommand(), True), BaseCommand)
command.Execute()
Next
End Sub
MustInherit Class BaseCommand
Public MustOverride Sub Execute()
End Class
Class Sub_1
Inherits BaseCommand
Public Overrides Sub Execute()
Console.WriteLine("Sub_1")
End Sub
End Class
Class Sub_2
Inherits BaseCommand
Public Overrides Sub Execute()
Console.WriteLine("Sub_2")
End Sub
End Class
Class Sub_3
Inherits BaseCommand
Public Overrides Sub Execute()
Console.WriteLine("Sub_3")
End Sub
End Class
Function GetCommand() As String
Return _typeLookup(_commandNames(_rand.Next(0, _commandNames.Length)))
End Function
End Module
Simple console app... In one app, where I used this, was in a server
application. The client would send a command and it's parameters in a
delimited sting something like:
DO_COOL_STUFF
aram1,param2,param3,param4
The server would get the command name, look up the class associated with that
command in the dictionary and then execute the sub by passing in the param
string. Worked great - and no big supper switch statement
Anyway, you can be creative
I have some dynamic validation logic that does
a similar thing, but looks up the class names in a database...