测试类类型是否可以使用 Activator 实例化而不实例化它
本文关键字:实例化 Activator 类型 是否 可以使 测试类 | 更新日期: 2023-09-27 18:37:02
当前当我有一个类类型并且需要知道是否可以创建该类时。我会打电话给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
}
使用 System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type) 将实例化对象,但不会调用构造函数。它呈现类的清零实例。该类必须是可访问的,否则将引发异常。如果您的类具有详细的启动代码,那么这可能会提高效率。