目前,当我有一个类类型并且需要知道是否可以创建该类时。我将致电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);
}
根据此处的内容,您可以测试类型是否包含无参数构造函数(默认情况下将提供无类的类),以及类型是否不是抽象的:
if(classType.GetConstructor(Type.EmptyTypes) != null && !classType.IsAbstract)
{
//this type is constructable with default constructor
}
else
{
//no default constructor
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句