简体   繁体   English

将文本框编号添加到数组C#

[英]add textbox number to array c#

I'm trying to make this program where a user will input a number in a textbox and it will store it into an array. 我正在尝试制作此程序,以便用户在文本框中输入数字并将其存储到数组中。

So whenever the user clicks "calculate", it will get an average of all the numbers in the array. 因此,每当用户单击“计算”时,它将获得数组中所有数字的平均值。 For some reason, when I try to run it, I get: 由于某种原因,当我尝试运行它时,我得到:

Additional information: Object reference not set to an instance of an object. 附加信息:对象引用未设置为对象的实例。

But then I can't initialize the array to specific length because I don't know how many numbers the user will input. 但是然后我无法将数组初始化为特定长度,因为我不知道用户将输入多少个数字。 So I was wondering is there a way to make it work without initializing a specific length for the array? 所以我想知道是否有一种方法可以使它工作而无需初始化数组的特定长度?

double[] numArray;
int count=0;

private void button1_Click(object sender, EventArgs e)
    {
        numArray[count] = convert.ToDouble(textBox1.Text);
        count++;
        displayNum.Visible = true;
        displayNum.Text = count.ToString();
         ;
    }

Why are you using array if you don't know the size? 如果不知道大小,为什么要使用数组? Use list instead. 请改用列表。

Initialization: 初始化:

List<double> numList = new List<double>();

Adding to list: 新增至清单:

numList.Add(some_element);

Use a IList/List as these start off with a size but if you fill it up they will automatically grab more memory and grow. 使用IList / List,因为它们以一个大小开始,但是如果将其填满,它们将自动获取更多内存并增长。

IList<double> numArray = new List<double>(); 
int count=0;

private void button1_Click(object sender, EventArgs e)
{
    numArray.Add(convert.ToDouble(textBox1.Text));
    count++;
    displayNum.Visible = true;
    displayNum.Text = count.ToString();
}

This is not possible with an array. 使用数组是不可能的。 An array needs to be initialized with the number of array items. 数组需要使用数组项的数量进行初始化。 Instead of an array I would suggest using List . 我建议使用List而不是数组。 This way you can add to the list without the restriction of defining how many items will be in it. 这样,您可以添加到列表中,而无需定义其中将包含多少项。 If you need an array after you populated the I believe there is a ToArray method off of List. 如果您在填充后需要一个数组,我相信List之外还有一个ToArray方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM