会员
周边
众包
新闻
博问
闪存
赞助商
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
无敌风火轮
博客园
首页
新随笔
联系
订阅
管理
根据字符串创建类实例(支持全名和部分名)
//
根据字符串创建类实例
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
佩恩
阅读(
857
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部