Nehmen wir folgenden Fall an: Der Name einer Klasse liegt als string vor und es gilt eine Instanz der Klasse zu erzeugen.
Das kann zum Beispiel so funktionieren:
1 2 3 4 5 6 | // you got the name of the class from somewhere string className = "Message" ; // create the type of the class using the destinated namespace var type = Type.GetType( "ValueObjects." + className, false ); // create the instance now var message = Activator.CreateInstance(type) as Message; |
In ASP.Net funktioniert das allerdings nicht. Hier ist ein Workarund über den BuildManager (using System.Web.Compilation) notwendig:
1 2 3 4 5 6 | // you got the name of the class from somewhere string className = "Message" ; // create the type of the class using the destinated namespace var type = BuildManager.GetType( "ValueObjects." + className, false ); // create the instance now var message = Activator.CreateInstance(type) as Message; |