gpt4 book ai didi

c# - Activator.CreateInstance 在转换到同一个程序集中的接口(interface)时出错

转载 作者:太空宇宙 更新时间:2023-11-03 12:51:56 25 4
gpt4 key购买 nike

我有一个名为 Base.Core.Boostrapper 的类,它实现了接口(interface) 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”

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

编辑:

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

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

谢谢

最佳答案

很可能有不止一个 INinjectModuleBootstrapper 并且由于您比较只是接口(interface)代码的名称 可能会找到错误的代码。

您应该确保所有程序集中只有一种类型,因为类型标识包括名称和程序集,而不仅仅是名称。

或者,您可以直接匹配类型或使用 FullName,但它可能找不到任何东西,因为代码正在寻找错误的接口(interface)。

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

关于c# - Activator.CreateInstance 在转换到同一个程序集中的接口(interface)时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35207801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com