TypeLoadException on Assembly.GetType 显式接口实现
本文关键字:显式接口实现 GetType Assembly on TypeLoadException | 更新日期: 2023-09-27 18:30:52
这是我的问题。 我有一个复杂的接口和抽象类的架构,我试图通过Assembly.LoadFrom("x.dll")加载它们。 当某些具有接口实现的类型(其中实现在基类中显式)尝试加载时,我得到一个 TypeLoadException,说:
来自程序集"MyPart2Assembly, version..."的类型"MyPart2DerivedType"中的方法"MyMethod"没有实现。 我试图理解为什么会这样,因为我已经浏览了几篇文章,甚至尝试手动删除 obj 文件和 dll。 以下是我到目前为止所做的事情的参考资料:
TypeLoadException 的解决方案
TypeLoadException说"没有实现",但它已经实现
Visual Studio Forumns: TypeLoadException
专用访问器和显式接口实现
所以这是我的示例代码:
//This is in project 1
public interface IFooPart1
{
void DoStuff();
}
//This is in project 2
public interface IFooPart2
{
void DoOtherStuff();
}
//This is in project 3
public interface IFooPart3: IFooPart1, IFooPart2
{
void DoEvenMoreStuff();
}
//This is in project 4
public abstract class MyBaseType: IFooPart1, IFooPart2
{
void IFooPart1.DoStuff()
{
DoStuffInternal();
}
void IFooPart2.DoOtherStuff()
{
DoOtherStuffInternal();
}
}
//This is in project 5
public class MyDerivedType: MyBaseType, IFooPart3
{
public void DoEvenMoreStuff()
{
//Logic here...
}
}
//Only has references to projects 1, 2, & 3 (only interfaces)
public class Program
{
void Main(params string[] args)
{
//Get the path to the actual dll
string assemblyDll = args[0];
//Gets the class name to load (full name, eg: MyNameSpace.MyDerivedType)
string classNameToLoad = args[1];
//This part works...
var fooAssembly = Assembly.LoadFrom(assemblyDll);
//Here we throw a TypeLoadException stating
// Method 'DoStuff' in type 'MyDerivedType' from assembly 'Project 5...' does
// not have an implementation.
Type myDerivedTypeExpected = Assembly.GetType(classNameToLoad);
}
}
注意:如果我将显式实现移动到MyDerivedType而不是MyBaseType,它可以工作...但我不明白为什么我必须这样做。 看来我应该可以。 此代码只是一个示例,实际代码有一个工厂,该工厂返回加载的类,但仅通过接口类型返回。(例如:var myDerivedType = GetInstance();)
对于每个对我的愚蠢修复感兴趣的人来说都好的。 这是我的问题:
Project6(这是控制台应用)具有对其他项目的 PROJECT 引用,而不是对它们应该生成到的位置中的 dll 的引用。 其他项目实际上是在特定的存储库区域构建的。 因此,控制台应用程序在尝试自动加载依赖项时使用的是自己的 dll 版本。 这显然使一些其他类型的方式被动态加载为不加载,因为它与那里的 dll 不在同一文件夹中......
简而言之,Assembly.LoadFrom 可能会导致您加载程序集两次,但 .NET 将其视为不同的程序集!! 在尝试动态加载类型时,这可能会引入一些真正的奇怪错误!!
请从我的沮丧/错误中吸取教训。 恶魔不会让朋友独自DI(代码审查是抓住这些愚蠢东西的关键)。
我遇到了类似的问题,因为我的一个项目引用了旧版本的 nuget 包依赖项。旧版本没有其中一个方法的实现。