为什么 Activator.CreateInstance 找不到构造函数

本文关键字:构造函数 找不到 CreateInstance Activator 为什么 | 更新日期: 2023-09-27 18:32:12

我在运行时加载一个DLL。 DLL 和主应用程序都使用 DLL 女巫持有接口,让程序知道如何使用 DLL 中的某些类型。 在主应用程序中有一个工厂类,Dll 可以在其中设置在主应用程序请求其继承的接口时要创建的对象类型之一。下面是从 DLL 创建对象类型的函数的条带化(主要是删除的错误处理代码)版本。 当它被调用时,我得到一个异常,说没有为此对象定义无参数构造函数。 我不知道为什么,因为它们都有无参数构造函数。

    //inside the DLL
    Factory.ResovleType<ISomething>(typeof(SomethingCool));
    //inside the main application
    ISomething obj = Factory.CreateObject<ISomething>();

    //inside the Factory Class
    public static T CreateObject<T>(params object[] args) 
    {
        T obj = (T)Activator.CreateInstance(resovledList[typeof(T)], args);
        return obj;
    }
    public static void ResolveType<T>(Type type)
    {
          resovledList.Add(typeof(T), type);

为什么 Activator.CreateInstance 找不到构造函数

从评论:

resovledList[typeof(T)]找到的类型不是预期的类型。相反,它是RuntimeType.这可能是调用ResolveType<ISomething>(typeof(Something).GetType())而不是ResolveType<ISomething>(typeof(Something))的结果:

typeof(Something)Type 类型的值(实际上是 RuntimeType ,它派生自 Type ),因此调用 typeof(Something).GetType() 会给你typeof(RuntimeType)

事实证明,您实际上是在其他地方打电话给GetType(),但问题和解决方案是一样的:您不应该在这里打电话给GetType()