用反射. 一个小例子. class Program { public static void Main(String[] args) { string FruitName = Console.ReadLine(); IFruit MyFruit; FruitFactory MyFruitFactory = new FruitFactory(); MyFruit = MyFruitFactory.MakeFruit("tmConsoleApp." +FruitName); //必须使用名称空间+类名称 Console.ReadLine(); } } public interface IFruit { }
public class Orange:IFruit { public Orange() { Console.WriteLine("An orange is got!"); } } public class Apple:IFruit { public Apple() { Console.WriteLine("An apple is got!"); } } public class FruitFactory { public IFruit MakeFruit(string Name) { IFruit MyFruit = null; try { System.Type type = System.Type.GetType(Name, true);//必须使用名称空间+类名称 MyFruit = (IFruit)Activator.CreateInstance(type); return MyFruit; } catch (TypeLoadException e) { Console.WriteLine("dont know this kind of fruit,exception caught - {0}", e.Message); return MyFruit; } } }
参考 使用反射生成一个窗体的例子: Assembly assm = Assembly.LoadFrom("e:\\WindowsApplication.dll"); Type TypeToLoad= assm.GetType("WindowsApplication.Form1");
object obj; obj = Activator.CreateInstance(TypeToLoad); Form formToShow = null; formToShow = (Form)obj; formToShow.Show();另外参考, http://www.c-sharpcenter.com/CSNET/dynamicinvoke.asp http://www.c-sharpcorner.com/Code/2002/April/LoadingAssemblyInfo.aspDynamically load a class and execute a method in .NET http://www.codeproject.com/csharp/DynLoadClassInvokeMethod.asp
http://topic.csdn.net/u/20080305/17/815d3d0c-bf27-4f8b-860f-7166a149cba2.html
一个小例子.
class Program
{
public static void Main(String[] args)
{
string FruitName = Console.ReadLine();
IFruit MyFruit;
FruitFactory MyFruitFactory = new FruitFactory();
MyFruit = MyFruitFactory.MakeFruit("tmConsoleApp." +FruitName); //必须使用名称空间+类名称 Console.ReadLine();
}
} public interface IFruit
{ }
public class Orange:IFruit
{
public Orange()
{
Console.WriteLine("An orange is got!");
}
} public class Apple:IFruit
{
public Apple()
{
Console.WriteLine("An apple is got!");
}
} public class FruitFactory
{
public IFruit MakeFruit(string Name)
{
IFruit MyFruit = null;
try
{
System.Type type = System.Type.GetType(Name, true);//必须使用名称空间+类名称
MyFruit = (IFruit)Activator.CreateInstance(type);
return MyFruit;
}
catch (TypeLoadException e)
{
Console.WriteLine("dont know this kind of fruit,exception caught - {0}", e.Message);
return MyFruit;
}
}
}
使用反射生成一个窗体的例子:
Assembly assm = Assembly.LoadFrom("e:\\WindowsApplication.dll");
Type TypeToLoad= assm.GetType("WindowsApplication.Form1");
object obj;
obj = Activator.CreateInstance(TypeToLoad);
Form formToShow = null;
formToShow = (Form)obj;
formToShow.Show();另外参考,
http://www.c-sharpcenter.com/CSNET/dynamicinvoke.asp
http://www.c-sharpcorner.com/Code/2002/April/LoadingAssemblyInfo.aspDynamically load a class and execute a method in .NET
http://www.codeproject.com/csharp/DynLoadClassInvokeMethod.asp