使用ToString()执行WriteLine时的IndexOutOfRangeException

时间:2017-10-29 12:06:16

标签: c# tostring

我是初学者,在尝试使用此代码时寻求帮助。 "公共覆盖字符串ToString()"方法不应该被触及,因为这是正确的。但是代码会在下面返回错误。我可能做错了什么?

  

未处理的异常:System.IndexOutOfRangeException:数组索引超出范围。     在Jumppa..ctor(System.String nimi,System.String [] ajat,System.String [] paikat)[0x00000] in:0     在Jumppa.Main(System.String [] args)[0x00000] in:0   [ERROR]致命的未处理异常:System.IndexOutOfRangeException:数组索引超出范围。     在Jumppa..ctor(System.String nimi,System.String [] ajat,System.String [] paikat)[0x00000] in:0     在Jumppa.Main(System.String [] args)[0x00000] in:0

  Using System;
    using System.Collections.Generic;

class Jumppa
{
      public override string ToString()
  {
      string jumppa = nimi+"\najat:\n";
      for (int i=0; i < ajat.Length; i++)
      {
      jumppa+= ajat[i] + "\n";
      }

      jumppa += "\npaikat:\n";

      for (int i=0; i < paikat.Length; i++)
      {
      jumppa+= paikat[i] + "\n";
      }
      return jumppa;
   }

    public string nimi;
    public string[] ajat=new string[2];
    public string[] paikat=new string[2];


    public Jumppa(string nimi,string[] ajat,string[]paikat)
    {
    this.nimi = nimi;
    this.ajat[2] = ajat[2];
    this.paikat[2] = paikat[2];
    }

    public Jumppa jumppa(Jumppa J1)
    {
        return this;
    }


    static void Main(string[] args)

    {
    //System.Collections.ArrayList jumppa = new System.Collections.ArrayList();


        Jumppa[] J1=new Jumppa[3];

        J1[0]  = new Jumppa ("junior",new[] {"Wedn 9:30", "Frid 9:30"},new[]{"Gym", "Basement"});
        J1[1]  = new Jumppa ("adult",new[] {"Wedn 10:30", "Frid 10:30"},new[]{"Gym", "Basement"});
        J1[2]  = new Jumppa ("oldlady",new[] {"Wedn 11:30", "Frid 11:30"},new[]{"Gym", "Basement"});



    //jumppa.Add(J1);

        //for (int i=0; i<2; i++)
        //{
    Console.WriteLine(J1[0].jumppa(J1[0]));
        //}
        return;   
        }

    }

1 个答案:

答案 0 :(得分:3)

问题在于以下几点:

this.ajat[2] = ajat[2];
this.paikat[2] = paikat[2];

ajatpaikat初始化为长度为2,因此有效索引为0和1.访问索引2会导致IndexOutOfRangeException。我怀疑你真正想做的是:

this.ajat = ajat;
this.paikat = paikat;