• 根据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;
     }
  • 相关阅读:
    注册表命令大全(二)
    让电脑定时关机
    NSIS nsDialogs 插件
    poj_1562Oil Deposits
    hdoj_1342Lotto
    VS 生成事件文件拷贝
    poj_1111Image Perimeters
    模拟求解迷宫问题(DFS+BFS)
    VS2010如何为所有工程配置环境
    POJ 并查集 题目汇总 ——czyuan原创
  • 原文地址:https://www.cnblogs.com/DoNetCShap/p/2564491.html
Copyright © 2020-2023  润新知