JAL Computing
|
Chapter 20 "Loading a Class By Name"A problem that comes up repeatedly is how to load a class dynamically at run time given the name of the class (as a string) and the name of the assembly that contains the class (eg. AssemblyName.dll). Note: In a sense, the runtime fully qualified name is the assembly name pre-pended to the fully qualified class name. There are basically two approaches to loading a class by name. The first approach is to get a Type using one of the GetType calls:
You can then create an instance of the class by calling System.Activator.CreateInstance(myType). The second approach is to pass the name of the assembly and the fully qualified name of the class directly to System.Activator.CreateInstance. Using Type.GetTypeTo use Type.GetType, you need to include the assembly name in the string as in "DrawablePlugins.Triangle,DrawablePlugIns". Here is a snippet of code that calls Type.GetType: string typeName="DrawablePlugIns.Triangle,DrawablePlugIns"; Using myAssembly.GetTypeIf you have access to the assembly, you can call assembly.GetType(string). //Assembly assembly= Assembly.GetExecutingAssembly();Assembly assembly= Assembly.Load("DrawablePlugIns"); Type assemblyType= assembly.GetType("DrawablePlugIns.Triangle"); System.Console.WriteLine(assemblyType); Using myModule.GetTypeFinally, you can call get type on a module as in: Using Activator.CreateInstance(string,string)As mentioned, the second approach is to pass the name of the assembly and the fully qualified name of the class directly to System.Activator.CreateInstance as in: object oByName= System.Activator.CreateInstance("DrawablePlugIns","DrawablePlugIns.Triangle"); Note: If the class exist in the executing assembly, then you can simply pass null for the assemblyName.
|
Send mail to [email protected]
with questions or comments about this web site. Copyright © 2001, 2002, 2003,
2004, 2005, 2006, 2007, 2008, 2009 ©
|