目前我有一个类类型,需要知道是否可以创建类。我会打电话给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);
}
答案 0 :(得分:8)
根据可以找到的内容here,您可以测试该类型是否包含无参数构造函数(默认情况下,未提供哪些类),以及该类型是否不是抽象的:
if(classType.GetConstructor(Type.EmptyTypes) != null && !classType.IsAbstract)
{
//this type is constructable with default constructor
}
else
{
//no default constructor
}
答案 1 :(得分:2)
使用System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type)将实例化对象,但不会调用构造函数。它呈现类的清零实例。该类必须是可访问的或抛出异常。如果您的类具有详细的启动代码,那么这可能会提高效率。