生成多个类对象

时间:2018-02-18 22:02:40

标签: c# list file loops class

我试图生成多个类对象,但是我得到了一个" System.ArgumentOutOfRangeException:'索引超出了范围。"此行的消息:clients [i] = new IRCClient(credentials,textEdit1.Text);

  public void FileRead()
    {
        if (File.Exists(AccountsFile))
        {
            Account.Clear();
            using (StreamReader Reader = new StreamReader(AccountsFile))
            {
                string line;
                while ((line = Reader.ReadLine()) != null)
                {
                    Account.Add(new Accounts { Username = line.Split(':')[0], Password = line.Split(':')[1] });
                }
            }
        }
        else
        {
            File.Create(AccountsFile);
        }
    }

   private void simpleButton1_Click(object sender, EventArgs e)
    {
        clients = new List<IRCClient>();
        int num = 7;
        foreach (var acc in Account)
        {
            for (int i = 0; i < num; i++)
            {
                credentials = new ConnectionCredentials(acc.Username, acc.Password);
                clients[i] = new IRCClient(credentials, textEdit1.Text); //exception thrown
                clients.Add(clients[i]);
                foreach (var c in clients)
                {
                    c.Connect();
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

List<T>与T []不同。即列表与数组不同,并且具有一些不同的行为。

myarray[i] = someValue;

对于数组,这将为数组的位置i添加一些值。但请记住阵列是预先启动的

myarray = new object[10];

只要i&gt; = 0且&lt; 10上面的代码没问题。

但是列表是不同的,并且可以(在您的情况下)初始化为空。然后他们会在需要时变得更大。它的好处之一(但也可能是性能损失)

所以当你这样做时:

clients = new List<IRCClient>();

您正在创建一个空列表,其中没有任何内容,因此它没有索引,所以当您这样做时:

clients[i] 

“i”处没有任何内容,所以你得到了那个例外。

正确使用

clients.Add(new IRCClient(credentials, textEdit1.Text))