我们的测试机器上有个很奇怪的bug。错误是:

系统。来自程序集“activeviewer(…)”的类型“DummyItem”中的方法“SetShort”没有实现。

我就是不明白为什么。SetShort在DummyItem类中,我甚至重新编译了一个版本,写入事件日志,只是为了确保它不是部署/版本控制问题。奇怪的是,调用代码甚至不调用SetShort方法。


当前回答

FWIW,当有一个配置文件重定向到引用程序集的不存在版本时,我得到了这个。融合日志为胜利而战!

其他回答

还有另一种方法:

class GenericFoo<T> {}

class ConcreteFoo : GenericFoo<ClassFromAnotherAssembly> {}

程序集中的代码,不引用ClassFromAnotherAssembly的程序集。

var foo = new ConcreteFoo(); //kaboom

当ClassFromAnotherAssembly是ValueTuple时,这发生在我身上。

我在运行单元测试时也遇到了这个问题。应用程序运行良好,没有错误。 在我的案例中,问题的原因是我关闭了测试项目的构建。 重新启用我的测试项目的构建解决了这些问题。

注:如果这个答案对你没有帮助,请花点时间向下滚动人们添加的其他答案。

简短的回答

如果将方法添加到一个程序集中的接口,然后再添加到另一个程序集中的实现类,但在没有引用接口程序集中的新版本的情况下重新构建实现程序集中,就会发生这种情况。

在本例中,DummyItem实现了来自另一个程序集的接口。SetShort方法最近被添加到接口和DummyItem中—但是包含DummyItem的程序集是引用先前版本的接口程序集重新构建的。因此SetShort方法有效地存在,但没有将其链接到接口中的等效方法。

长回答

如果你想尝试复制这个,试试下面的方法:

Create a class library project: InterfaceDef, add just one class, and build: public interface IInterface { string GetString(string key); //short GetShort(string key); } Create a second class library project: Implementation (with separate solution), copy InterfaceDef.dll into project directory and add as file reference, add just one class, and build: public class ImplementingClass : IInterface { #region IInterface Members public string GetString(string key) { return "hello world"; } //public short GetShort(string key) //{ // return 1; //} #endregion } Create a third, console project: ClientCode, copy the two dlls into the project directory, add file references, and add the following code into the Main method: IInterface test = new ImplementingClass(); string s = test.GetString("dummykey"); Console.WriteLine(s); Console.ReadKey(); Run the code once, the console says "hello world" Uncomment the code in the two dll projects and rebuild - copy the two dlls back into the ClientCode project, rebuild and try running again. TypeLoadException occurs when trying to instantiate the ImplementingClass.

I had the same problem. I figured out that my assembly, which is loaded by the main program, had some references with "Copy Local" set to true. These local copies of references were looking for other references in the same folder, which did not exist because the "Copy Local" of other references was set to false. After the deletion of the "accidentally" copied references the error was gone because the main program was set to look for correct locations of references. Apparently the local copies of the references screwed up the sequence of calling because these local copies were used instead of the original ones present in the main program.

重要的信息是,出现此错误是因为缺少加载所需程序集的链接。

以下是我对这个错误的看法。

添加了一个extern方法,但我的粘贴是错误的。DllImportAttribute被放到一个注释出来的行。

/// <returns>(removed for brevity lol)</returns>[DllImport("user32.dll")] 
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindowVisible(IntPtr hWnd);

确保属性实际包含在源代码中解决了这个问题。