我使用自己的 IComparer 对列表进行排序,并且在运行应用程序(XNA 游戏)超过一个小时时效果很好。但是,突然之间,在使用自定义比较器调用排序方法时,有时会出现以下错误:
An unhandled exception of type 'System.ArgumentException' occured in mscorlib.dll
Additional Information: ArgumentException
这是引发异常的行:
List<Continent> markets = new List<Continent>();
// filling the markets list ...
markets.Sort(new MarketCostCoverComparer(this));
这是我实现 IComparer 接口的类:
class MarketCostCoverComparer : IComparer<Continent> {
private Player player;
public MarketCostCoverComparer(Player player) {
this.player=player;
}
public int Compare(Continent c1, Continent c2) {
if(player.GetCostCovering(c1)<player.GetCostCovering(c2)) {
return +1;
} else if(player.GetCostCovering(c1)==player.GetCostCovering(c2)) {
return 0;
} else {
return -1;
}
}
}
这里有一些链接到比较器的方法......:
public float GetCostCovering(Continent continent) {
// cover<1 => bad | cover>1 => good
if(GetOilfieldTheoreticOutput(continent.Type, true)<continent.Economy.CurrentDemand) {
return ((float)((GetOilfieldTheoreticOutput(continent.Type, true)*continent.Economy.CurrentPrice)))/(float)GetOilfieldCosts(continent.Type, true);
} else {
return ((float)((continent.Economy.CurrentDemand*continent.Economy.CurrentPrice)))/(float)GetOilfieldCosts(continent.Type, true);
}
}
public int GetOilfieldTheoreticOutput(ContinentType continent, bool drilled) {
int total = 0;
foreach(Oilfield oilfield in worldmap.Continents[(int)continent].Oilfields) {
if(oilfield.Owner==this && oilfield.Drilled==drilled) {
total+=oilfield.TheoreticOutput;
}
}
return total;
}
public int GetOilfieldCosts(ContinentType continent, bool drilled) {
int total = 0;
foreach(Oilfield oilfield in worldmap.Continents[(int)continent].Oilfields) {
if(oilfield.Owner==this && oilfield.Drilled==drilled) {
total+=oilfield.Costs;
}
}
return total;
}
这是异常的屏幕截图:
这里仔细看看 Locals/Stack-Trace(这是一个旧的屏幕截图,但我会在接下来的几个小时内尝试重现这个异常,以便我可以展开跟踪):