• 根据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;
     }

  • 相关阅读:
    IceMx.Mvc 我的js MVC 框架 二、视图的数据绑定
    IceMx.Mvc 我的js MVC 框架 一、html代码的分离(视图)
    Android Socket编程基础
    第七次作业
    第六次作业
    第五次作业
    第4次作业
    关于个人项目的总结,最主要是不足
    第二次作业
    微信的优缺点以及发展史
  • 原文地址:https://www.cnblogs.com/jobs/p/22200.html
Copyright © 2020-2023  润新知