日期:2014-05-18 浏览次数:21007 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication1 { public interface ICar { void Say(); } public class Bus : ICar { public void Say() { Console.WriteLine("I am a Bus"); } } public class Truck : ICar { public void Say() { Console.WriteLine("I am a Truck"); } } public class CarFactory { public static ICar BuildCar(string name) { ICar myCar = null; try { Type type = Type.GetType(name, true); myCar = (ICar)Activator.CreateInstance(type); } catch (TypeLoadException e) { Console.WriteLine("Unknow Car. Exception: - {0}", e.Message); } return myCar; } } class Program { static void Main(string[] args) { Console.WriteLine("Programm Started:"); Console.WriteLine("---------------------------------------"); Console.WriteLine(""); string strClass = "Bus"; ICar myCar = CarFactory.BuildCar(strClass); //myCar.Say(); Console.WriteLine(""); Console.WriteLine("---------------------------------------"); } } }