为什么使用 Moq 创建的模拟实例会抛出 System.BadImageFormatException?

发布于 2024-07-20 19:03:17 字数 1070 浏览 7 评论 0原文

这个问题可能与另一个问题相关,并且它肯定会导致 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(),这可以正确重现问题。 安装 GDR 后,此问题仍然存在。

编辑:似乎如果对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷爱 2024-07-27 19:03:17

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文