【问题标题】:Test if a class type can be instantiated with Activator without instantiating it测试一个类类型是否可以在不实例化的情况下用 Activator 实例化
【发布时间】:2013-10-26 20:25:25
【问题描述】:

目前当我有一个类类型并且需要知道该类是否可以创建时。我会打电话给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);
        }

【问题讨论】:

    标签: c# .net instantiation reflector


    【解决方案1】:

    根据here的内容,你可以测试该类型是否包含无参数构造函数(没有提供时默认哪些类),以及该类型是否不是抽象的:

    if(classType.GetConstructor(Type.EmptyTypes) != null && !classType.IsAbstract)
    {
         //this type is constructable with default constructor
    }
    else
    {
       //no default constructor
    }
    

    【讨论】:

    • 我认为除了检查是否有参数构造函数而不是抽象之外,我们应该检查类型是否不是静态的。
    • @Parsa,静态类没有实例构造函数,因此 GetConstructor 将为空。最好检查一下类是否是泛型的。
    【解决方案2】:

    使用System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type) 将实例化对象但不会调用构造函数。它呈现一个归零的类实例。该类必须是可访问的,否则会引发异常。如果您的课程有冗长的启动代码,那么这可能会提高效率。

    【讨论】:

      猜你喜欢
      • 2022-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 2022-08-10
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多