今天我遇到了一个我能够解决的非常奇怪的问题,但我仍然不明白为什么会这样。这是场景:
编辑
我把场景改得更简单了: 我有一个执行代码的程序和 2 个导入器,一个具有泛型类型的基类和另一个只调用基方法并对其进行迭代的类 (ImplementingImporter)。 这是完整的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IEnumeratorLoadProblem {
class Program {
static void Main(string[] args) {
var importer = new ImplementingImporter();
try {
var data = importer.GetData().ToArray();
} catch (BadImageFormatException ex) {
Console.WriteLine("Why does this fail? " + ex.ToString());
}
Console.WriteLine("Press enter to quit");
Console.ReadLine();
}
}
class BaseClassImporter<T> {
public virtual IEnumerable<T> GetData() {
yield break;
}
}
class ImplementingImporter : BaseClassImporter<int> {
public override IEnumerable<int> GetData() {
// iterating seems to cause the problem
foreach(var dataByBaseImpl in base.GetData()) {
yield return dataByBaseImpl;
}
}
}
}
我收到以下错误:
System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
当我将使用过的导入器的代码更改为有效时:
class ImplementingImporter : BaseClassImporter<int> {
protected override IEnumerable<int> GetData() {
return base.GetData();
}
}
不幸的是,我无法查看生成的 IL 代码,因为 ILSpy 和 Reflector.NET(版本 6)都显示了一个内部错误(我认为这是一个 ArgumentOutOfRangeException)。不敢用ildasm,所以没有尝试直接看IL Code。
我猜它与生成的 IL 代码有关,但我想不出导致问题的场景。
知道这里发生了什么吗? 如果场景不够清晰,请发表评论,我会尽量使其更清晰。
编辑:
使用的 .NET 版本:4.0。该应用程序是一个使用 VS 2010 SP1 的控制台应用程序。 Build Platform 目标是 AnyCPU,但使用 x86 时也会出现问题。 我的机器有 64 位系统 (Windows 7)。 使用 .NET 4.0 客户端配置文件时也会发生异常。
该示例是单个项目,没有使用外部/非托管库,因此不应出现建议的问题(例如,在运行 64 位时引用 32 位程序集)。
最佳答案
这似乎是 yield return
语句的错误:
他们说它在 VS2012(或“VS 2010 之后的版本”)中已修复。
我正在使用 VS2010 SP1 运行针对 .NET Framework 4 的控制台应用程序,可以确认我遇到了与您相同的错误。我没有可用于尝试此操作的 VS2012 安装。
这里问了一个类似的问题:
Iterator blocks and inheritance
另一个可疑的相似示例(这次使用异步,但再次在 MoveNext
上触发):
C#5 AsyncCtp BadImageFormatException
其他资源:
关于c# - 使用 IEnumerable 和多重继承时出现 BadImageFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11953153/