c# – 测试是否可以使用Activator实例化类类型而不实例化它

前端之家收集整理的这篇文章主要介绍了c# – 测试是否可以使用Activator实例化类类型而不实例化它前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我有一个类类型,需要知道是否可以创建类.我将调用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);
        }

解决方法

根据可以找到的内容 here,您可以测试该类型是否包含无参数构造函数(默认情况下,未提供哪些类),以及该类型是否为抽象:
if(classType.GetConstructor(Type.EmptyTypes) != null && !classType.IsAbstract)
{
     //this type is constructable with default constructor
}
else
{
   //no default constructor
}
原文链接:https://www.f2er.com/csharp/91625.html

猜你在找的C#相关文章