根据字符串创建类实例(支持全名和部分名)



//根据字符串创建类实例   
            object obj;        

            
//如果是类的全名(加了命名空间) 
            string classFullName = "反射2222.Class1" ; 
            obj 
= System.Activator.CreateInstance( Type.GetType( classFullName) );

            
//如果不是类的全名(加了命名空间),则需要以下方法

            
//ClassLibrary1.Class1 位于另一个DLL类库中
            
//当前Exe程序中有也有一个类,名为 class1,模拟类名范围不明确的问题
            
//以下一句确保类库被加载到内存
            string s = ClassLibrary1.Class1.a;

            
string className = "class1" ;
            Assembly[] assemblys 
= AppDomain.CurrentDomain.GetAssemblies();
            
bool is_find = false;
            
foreach (Assembly a in assemblys)
            
{
                
if (a.GlobalAssemblyCache)
                    
continue;
                Type[] types 
= a.GetTypes();

                
foreach (Type t in types)
                
{
                    
string tmp = t.ToString();
                    
int i = tmp.LastIndexOf(className, StringComparison.OrdinalIgnoreCase);

                    
//确保匹配的是类名,而不是namespace
                    if (tmp.Length - className.Length == i)
                    
{
                        
if (!is_find)
                        
{
                            
//创建类实例
                            obj = a.CreateInstance(t.ToString());
                            is_find 
= true;
                            
//如果需要处理类库冲突,则不要中断循环
                            break;
                        }

                        
else
                        
{
                            
//如果需要处理类库冲突,则throw
                            
//throw new Exception("请使用更长的类限定名");
                        }

                    }

                }

            }
posted on 2007-12-06 21:57  佩恩  阅读(853)  评论(0编辑  收藏  举报