Rea*_*lar 9 .net c# reflector instantiation
目前我有一个类类型,需要知道是否可以创建类.我会打电话Activator.CreateInstance(type);扔掉结果.
这似乎非常低效且有问题.
是否有另一种方法可以确认是否可以为当前应用程序实例化类类型?
作为应用程序启动的一部分,我需要进行此测试.确保尽早发现任何错误配置.如果我离开它直到需要类的实例,那么当没有人来修复它时可能会发生错误.
这就是我现在所做的.
string className = string.Format("Package.{0}.{1}", pArg1, pArg2);
Type classType = Type.GetType(className);
if (classType == null)
{
throw new Exception(string.Format("Class not found: {0}", className));
}
try
{
// test creating an instance of the class.
Activator.CreateInstance(classType);
}
catch (Exception e)
{
logger.error("Could not create {0} class.", classType);
}
Run Code Online (Sandbox Code Playgroud)
biz*_*dee 10
基于此处可以找到的内容,您可以测试该类型是否包含无参数构造函数(默认情况下,未提供哪些类),以及该类型是否为抽象:
if(classType.GetConstructor(Type.EmptyTypes) != null && !classType.IsAbstract)
{
//this type is constructable with default constructor
}
else
{
//no default constructor
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1743 次 |
| 最近记录: |