Loading

根据typeName获取Type较为完备的办法

前年还在开发.NET产品,我那时候编写一个C#脚本解释引擎,遇到一个问题是,Type.GetType()方法无法获取尚未装载类型。这些天,在阅读一些相关的代码时,得知了一种较为完整的方法,共享如下:

internal static Type FindTypeInCurrentDomain(string typeName)
 {
      Type type = null;
  
      //如果该类型已经装载
      type = Type.GetType(typeName);
      if (type != null)
      {
           return type;
      }

      //在EntryAssembly中查找
      if (Assembly.GetEntryAssembly() != null)
      {
           type = Assembly.GetEntryAssembly().GetType(typeName);
           if (type != null)
           {
                return type;
           }
      }

      //在CurrentDomain的所有Assembly中查找
      Assembly[] assemblyArray = AppDomain.CurrentDomain.GetAssemblies();
      int assemblyArrayLength = assemblyArray.Length;
      for (int i = 0; i < assemblyArrayLength; ++i)
      {
           type = assemblyArray[i].GetType(typeName);
           if (type != null)
           {
                return type;
           }
      }

      for (int i = 0; (i < assemblyArrayLength); ++i)
      {
           Type[] typeArray = assemblyArray[i].GetTypes();
           int typeArrayLength = typeArray.Length;
           for (int j = 0; j < typeArrayLength; ++j)
           {
                if (typeArray[j].Name.Equals(typeName))
                {
                     return typeArray[j];
                }
           }
      }

      return type;
 }

 

posted @ 2012-06-26 23:13  jevan  阅读(262)  评论(0编辑  收藏  举报