using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace FactoryPattern
{
    public interface IFruit
    {    }
    public class Orange : IFruit
    {
        public Orange()
        {
            Console.WriteLine("An Orange is got!");
        }    }
    public class Apple : IFruit
    {
        public Apple()
        {
            Console.WriteLine("A apple is got!");
        }
    }    public class FruitFactory
    {
        public IFruit MakeFruit(string Name)
        {
            IFruit MyFruit = null;
            try
            {
                Type type = Type.GetType(Name,true);//***********
                MyFruit = (IFruit)Activator.CreateInstance(type);
            }            catch (TypeLoadException e)
            {
                Console.WriteLine("I dont know this kind of fruit,exception caught - {0}", e.Message);
            }
            return MyFruit;
        }
    }
    public class Program
    {
        public static void Main()
        {
            Console.Write("please input the fruit which you want to produce:");
            string fruitName = Console.ReadLine();
            FruitFactory factory = new FruitFactory();
                        factory.MakeFruit(fruitName);
                        Console.ReadLine();
        }
    }
}不知道为什么老是在“*************”处抛出异常
请问是什么原因阿 

解决方案 »

  1.   

    你的 输入有问题 要带namespace 一起 输入的 要输入:
    FactoryPattern.Orange
    FactoryPattern.Apple 
      

  2.   

    TYPE没有获得类型,需要 命名空间.类名,这样才能得到该类的类型,然后才能创建实例~
      

  3.   

    改成  Name = " FactoryPattern." + Name;
    应该就对了
      

  4.   

    System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom("ClassLibrary1.DLL");
    System.Type t = a.GetType("ClassLibrary1.Class1");
    Object theObj = System.Activator.CreateInstance(t);string path = System.Configuration.ConfigurationSettings.AppSettings["DAL"];
     string TypeName=path+".A"
     Type objType = Type.GetType(TypeName,true);
     return (IDbObject)Activator.CreateInstance(objType);