我不知道为什么我得到一个System.IndexOutOfRangeException? C#

时间:2016-04-04 11:13:57

标签: c#

我有以下代码:

public static KeyValuePair<string[], string[]> GetAccounts()
{   
    string[] usernames = { "user1", "user2", "user3" };
    string[] oauths = { "oauth1", "oauth2", "oauth3" };
    return new KeyValuePair<string[], string[]> (usernames, oauths);
}

然后我在Main()中调用该函数:

public static void Main(string[] args)
{
    KeyValuePair<string[], string[]> users = GetAccounts ();
    for (int i = 0; i <= users.Key.Length; i++) {
        Console.WriteLine (i);
        Console.WriteLine (users.Key.GetValue (i) + " " + users.Value.GetValue (i));
   }

}

但是,当我在第二个控制台写入行上获得System.IndexOutOfRangeException时。我不知道为什么这不起作用。我期待看到:

 user1 oauth1
 user2 oauth2
 user3 oauth3

3 个答案:

答案 0 :(得分:2)

for (int i = 0; i < users.Key.Length; i++)

更改&lt; =到&lt;在for语句中。

答案 1 :(得分:0)

变量i不能等于users.Key.Length

for (int i = 0; i <= users.Key.Length; i++)更改为for (int i = 0; i < users.Key.Length; i++)

答案 2 :(得分:0)

您正在获取System.IndexOutOfRangeException,因为您的for循环运行4次而不是3次,并且在最后一个循环中它搜索不存在的users.Key.GetValue(3)。

您可以使用以下代码来纠正

  for (int i = 0; i < users.Key.Length; i++) {
            Console.WriteLine (i);
            Console.WriteLine (users.Key.GetValue (i) + " " + users.Value.GetValue (i));
       }

for (int i = 0; i <= users.Key.Length-1; i++) {
            Console.WriteLine (i);
            Console.WriteLine (users.Key.GetValue (i) + " " + users.Value.GetValue (i));
       }
相关问题