zoukankan      html  css  js  c++  java
  • 根据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;
     }

  • 相关阅读:
    【排序】冒泡排序,C++实现
    【排序】选择排序,C++实现
    【排序】插入排序,C++实现
    【集成学习】 lightgbm原理
    leetcode1310
    leetcode1309
    leetcode1300
    leetcode1302
    leetcode1299
    leetcode1306
  • 原文地址:https://www.cnblogs.com/dingdingmao/p/3146617.html
Copyright © 2011-2022 走看看