I get an error: Additional information: Object reference not set to an instance of an object

I get an error: Additional information: Object reference not set to an instance of an object

我搜索了其他类似的错误,但没有找到任何解决方案。

public string[] vector;

//...

string comanda = "select * from chat";
MySqlConnection con = new MySqlConnection(conexiune);
MySqlCommand cmd = new MySqlCommand(comanda, con);
MySqlDataReader dr;
int i = 1;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
    if (dr[1].ToString().Length > 1)
    {
        if (i == 1)
        {
            textBox1.Text = dr[0].ToString() + ": " + dr[1].ToString();
        }
        else
        {
            textBox1.Text = textBox1.Text + "\r\n";
            textBox1.Text = textBox1.Text + dr[0].ToString() + ": " + dr[1].ToString();
        }
    }
    vector[i] = dr[1].ToString();
    i++; // Exception: An unhandled exception of type 'System.NullReferenceException' occured in Chat_1.exe   
}
con.Close();
timer1.Start();

请初始化您的向量。不使用 new with array 为 null。 将代码更改为 public string[] vector = new String[3]。请将 3 替换为您想要的尺寸。

您没有初始化数组。尝试在某处初始化它,例如构造函数中的方法或更好的方法:

vector = new string[number of how much elements you need];

虽然列表的默认长度为 4 并且可以自行调整大小,但数组可以指定其元素的数量或带有预定义的元素。

var vector = new string[] { "El 1", "El 2"...};