出界错误..为什么?

时间:2015-04-10 15:45:01

标签: c#

AssignCarsAndDrivers有一个索引越界错误,为什么?我这样做是为了工作,答案似乎超出了我的范围。

public void Rate()
{
  AssignCarsAndDrivers();
  UnderwritePolicy();
  RateLiability();
}

private void UnderwritePolicy()
{
    if (Policy.Car.ModelYear < 2010)
        throw new ApplicationException("Model year older than 2010.");
}

private void AssignCarsAndDrivers()
{
  if (Policy.Drivers.Count == 0)
    throw new ApplicationException("The policy must have at least one driver.");
  if (Policy.Cars.Count == 0)
    throw new ApplicationException("The policy must have at least one car.");
  for (int driverIndex = 0; driverIndex <= Policy.Drivers.Count; driverIndex++)
  {
    if (

1 个答案:

答案 0 :(得分:4)

它不应该小于或等于(&lt; =)&#34; ...尝试将其更改为&#34;小于(&lt;)&#34; ,因为driverIndex从 0 开始。

使用此:

for (int driverIndex = 0; driverIndex < Policy.Drivers.Count; driverIndex++)

相反:

for (int driverIndex = 0; driverIndex <= Policy.Drivers.Count; driverIndex++)