定义没有固定大小的双数组?

您好我的c#Arrays有问题。 我需要一个数组来存储一些数据…我的代码是那样的

double[] ATmittelMin; ATmittelMin[zaehlMittel] = Gradient(x, xATmax, y, yATmax); 

但编译器说:未定义var如何定义没有固定大小的双数组? 非常感谢!

数组总是固定大小,必须像这样定义:

 double[] items1 = new double[10]; // This means array is double[3] and cannot be changed without redefining it. double[] items2 = {1.23, 4.56, 7.89}; 

List类在后台使用数组,并在空间不足时重新定义它:

 List items = new List(); items.Add(1.23); items.Add(4.56); items.Add(7.89); // This will give you a double[3] array with the items of the list. double[] itemsArray = items.ToArray(); 

您可以像对待数组一样迭代List

 foreach (double item in items) { Console.WriteLine(item); } // Note that the property is 'Count' rather than 'Length' for (int i = 0; i < items.Count; i++) { Console.WriteLine(items[i]); } 

从我看到你没有声明zaehlMittel变量。 我想这就是编译器抱怨的内容。

除此之外,即使您当然可以以编程方式确定该变量的值,但是您想要创建数组的那一刻必须知道它的大小。 这是数组的工作方式。

如果你不能轻易做到这一点,我建议使用某种动态数据结构,如列表或集合。 然后,一旦添加了所有元素,你当然仍然可以自由地创建一个数组,就像那时你知道元素的数量一样(即使有像toArray()这样的便利方法甚至可以解决这个问题。 )。

您必须在使用之前实例化arrays:

 double[] ATmittelMin = new double[10]; ATmittelMin[zaehlMittel] = Gradient(x, xATmax, y, yATmax); 

想到的明显解决方案是使用List:

 List ATmittelMin = new List(); ATmittelMin.Add(Gradient(x, xATMax, y, yATMax); 

但是,如果您不想从列表转换为数组,则可以在以后增长数组:

 double[] ATmittelMin = new double[10]; // Some code int index = some_value; if (index >= TmittelMin.Length) { Array.Resize(ATmittelMin, index+5); // So we're not constantly resizing the array } 

这并不理想,因为你在幕后做了很多工作 – 可能比你更有效率。