所以这是我的问题。我有一个复杂的接口(interface)和抽象类架构,我试图通过 Assembly.LoadFrom("x.dll") 加载它们。当尝试加载具有接口(interface)实现(其中实现在基类中是显式的)的某些类型时,我收到 TypeLoadException 消息:
程序集“MyPart2Assembly,版本...”中类型“MyPart2DerivedType”中的方法“MyMethod”没有实现。我试图理解为什么会这样,因为我已经阅读了几篇文章,甚至试图手动删除 obj 文件和 dll。以下是我目前所做工作的引用资料:
TypeLoadException says 'no implementation', but it is implemented
Visual Studio Forumns: TypeLoadException
Private accessors and explicit interface implementation
所以这是我的示例代码:
//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,它会起作用……但我不明白为什么我必须这样做。看来我应该可以。此代码只是一个示例,实际代码有一个工厂返回加载的类,但仅通过接口(interface)类型。 (例如:var myDerivedType = GetInstance();)
最佳答案
对所有对我的愚蠢修复程序感兴趣的人来说都是好的。这是我的问题:
Project6(这是控制台应用程序)具有对其他项目的 PROJECT 引用,而不是对它们应该构建到的位置中的 dll 的引用。其他项目实际上正在构建到特定的存储库区域。因此,控制台应用程序在尝试自动加载依赖项时使用它自己的 dll 版本。这显然使一些正在动态加载的其他类型无法加载,因为它与那里的 dll 不在同一个文件夹中......
简而言之,Assembly.LoadFrom 可能会使您加载一个程序集两次,但 .NET 将其视为不同的程序集!!!这可能会在尝试动态加载类型时引入一些真正奇怪的错误!!!
请从我的挫折/错误中吸取教训。恶魔不要让 friend 独自进行 DI(代码审查是捕获这些愚蠢东西的关键)。
关于c# - Assembly.GetType 显式接口(interface)实现上的 TypeLoadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18721714/