为什么使用 Moq 创建的模拟实例会抛出 System.BadImageFormatException?
这个问题可能与另一个问题相关,并且它肯定会导致 System.BadImageFormatException。 也许是同一件事,但曝光不同?
我有以下代码:
public interface IFoo<T> where T : class, new() {
T FooMethod(object o);
}
public interface IFooRepo {
F GetFoo<T, F>() where T : class, new() where F : IFoo<T>;
}
然后我有一个使用 Moq 模拟 IFooRepo 的测试,如下所示:
var instance = new Mock<IFooRepo>().Object;
上面的代码运行良好,除非使用 Visual Studio 2008 调试测试。当我跨过上面的行时,系统会抛出 System.BadImageFormatException通过 Castle.DynamicProxy .Reflection.Emit。 这是否与 Ayende Rahien 发布的某些内容类似?
现在的解决方法是为 IFooRepo 实现一个假的,但我很好奇为什么会为这种情况生成不良图像,有解决办法吗? System.Reflection.Emit 有问题吗? 或者我在自己的代码中遗漏了一些明显的东西?
编辑:发布了 GetFoo() 的错误签名。 将签名更正为 GetFoo
编辑:似乎如果对 F 的约束包含类型参数 T BadImageFormatException 就会引发。 但我将其更改为 where F : class, new()
,然后一切都会按预期工作。
This question may be related to another question and it certainly results with a System.BadImageFormatException. Maybe it's the same thing but exposed differently?
I have the following the code:
public interface IFoo<T> where T : class, new() {
T FooMethod(object o);
}
public interface IFooRepo {
F GetFoo<T, F>() where T : class, new() where F : IFoo<T>;
}
Then I have a test that mocks IFooRepo using Moq like so:
var instance = new Mock<IFooRepo>().Object;
The above code runs fine except when debugging the test with Visual Studio 2008. When I step over the above line a System.BadImageFormatException is thrown from System.Reflection.Emit via Castle.DynamicProxy. Could this be similar to something Ayende Rahien posted?
Now the workaround is to implement a fake for IFooRepo but I'm curious as to why a bad image is generated for this kind of scenario and is there a fix? Is System.Reflection.Emit buggy? Or am I missing something obvious in my own code?
EDIT: Posted the incorrect signature for GetFoo(). Corrected the signature to GetFoo<T, F>(), which correctly reproduces the problem. With the GDR installed this problem persists.
EDIT: It seems that if the constraint on F includes type parameter T BadImageFormatException is raised. But I change it to, say where F : class, new()
, then everything works as expected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
FWIW,我同意 Ayende 的帖子解释了这种行为,并且只有当一个通用参数的约束引用另一个通用参数时才会发生这种情况。 我在东德也遇到过这种情况,并采用了相同的手工编码假货的解决方法。
FWIW, I agree that Ayende's post explains this behavior, and that it only happens when constraints on one generic parameter reference another. I encounter it, too, with the GDR, and have adopted the same workaround of hand-coded fakes.
您是否安装了.NET 3.5 SP1 GDR? 其一个已知问题
Did you install the .NET 3.5 SP1 GDR? its a know issue