Activator.CreateInstance 强制转换到同一程序集内的接口时出错

本文关键字:程序集 接口 出错 CreateInstance 转换 Activator | 更新日期: 2023-09-27 18:33:25

我有一个名为Base.Core.Boostrapper的类,它实现了接口Base.Core.INinjectModuleBootstrapper。它们都属于同一个Assembly Base.Core。

此代码有效

(INinjectModuleBootstrapper)Activator.CreateInstance(typeof(Bootstrapper));

虽然这个没有

 foreach (var assembly in assemblies)
            {
                assembly
                    .GetTypes()
                    .Where(t =>
                           t.GetInterfaces()
                               .Any(i =>
                                    i.Name == typeof(INinjectModuleBootstrapper).Name))
                    .ToList()
                    .ForEach(t =>
                    {
                            // throws error here when T == Base.Core.Boostrapper
                    (INinjectModuleBootstrapper)Activator.CreateInstance(t);
                    });
            }

引发错误:无法将类型为"Base.Core.Bootstrapper"的对象转换为类型"Base.Core.INinjectModuleBootstrapper"

为什么会这样?如果我将接口移动到具有不同命名空间的不同程序集,它不会引发任何异常。

编辑:

typeof (INinjectModuleBootstrapper) == t.GetInterfaces()[0];

其中 GetInterfaces() 的索引 0 是 INinjectModuleBootstrapper 不等于 INinjectModuleBootstrapper,即使 AssemblyQualifiedName、UnderlyingSystemType 和 GUID 相同!

谢谢

Activator.CreateInstance 强制转换到同一程序集内的接口时出错

很可能

有多个INinjectModuleBootstrapper并且由于您仅比较接口代码的名称可能会找到错误的一个。

应确保所有程序集中只有一个类型,因为类型标识包括 Name 和程序集,而不仅仅是 name。

或者,您可以直接匹配类型或使用 FullName,但它可能不会找到任何代码来查找错误的接口。

至于移动到不同的命名空间修复:很可能您的using Namespace语句使"错误"的INinjectModuleBootstrapper类型对按接口查找类型的代码可见。使用 Visual Studio 中的"转到定义"功能来验证代码中实际使用的类型(即,如果您有Lib1.INinjectModuleBootstrapperLib2.INinjectModuleBootstrapper,而不是取决于你有using Lib1;还是using Lib2;你会得到不同的类型来执行搜索)。