【问题标题】:generate multiple class objects生成多个类对象
【发布时间】:2018-07-29 03:38:00
【问题描述】:

我正在尝试生成多个类对象,但我收到“System.ArgumentOutOfRangeException: 'Index was out of range”。此行的消息: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();
                }
            }
        }
    }

【问题讨论】:

  • 您似乎误解了列表的工作原理。删除您的索引器(抛出的行),并直接添加对象:clients.Add(new IRCClient(credentials, textEdit1.Text));
  • 尽管如此,您的代码也没有多大意义。真的是要加7倍的账号吗?那个 7 是从哪里来的?
  • @KevinGosse 因为我正在尝试将 7 个机器人从文本文件连接到 IRC 聊天频道,哈哈。
  • 嘿@KevinGosse,你认为你可以在不和谐方面帮助我更多吗?

标签: c# list file loops class


【解决方案1】:

List&lt;T&gt; 与 T[] 不同。即列表与数组不同,有一些不同的行为。

myarray[i] = someValue;

对于数组,这将为数组的位置 i 添加一些值。但请记住,数组是预先初始化的

myarray = new object[10];

所以只要 i >= 0 且

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

所以当你这样做时:

clients = new List<IRCClient>();

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

clients[i] 

位置 'i' 没有任何东西,所以你得到那个异常。

正确的用法是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多