由于myArray1
和myArray2
都被定义为长度等于length
,因此除非您更改它,否则它们的长度将始终为 ,因为 IDE 逐行编译项目。length
0
0
但是,如果您愿意更改数组长度,您可以使用Array.Resize<T>(ref T[] array, int newSize)
wherearray
数组来调整大小,并且newSize
是数组的新长度。
例子
class myProject
{
public static int length = 0; //Initialize a new int of name length as 0
public static string[] myArray1 = new string[length]; //Initialize a new array of type string of name myArray1 as a new string array of length 0
public static string[] myArray2 = new string[length]; //Initialize a new array of type string of name myArray2 as a new string array of length 0
public static void setLength()
{
length = 5; //Set length to 5
}
public static void process()
{
setLength(); //Set length to 5
Array.Resize(ref myArray1, length); //Sets myArray1 length to 5
//Debug.WriteLine(myArray1.Length.ToString()); //Writes 5
}
注意:在大多数情况下,最好使用System.Collections.Generic.List<T>
它,因为它更易于管理和动态调整大小。
例子
List<string> myList1 = new List<string>(); //Initializes a new List of string of name myList1
private void ListItems()
{
AddItem("myFirstItem"); //Calls AddItem to add an item to the list of name myFirstItem
AddItem("mySecondItem"); //Calls AddItem to add an item to the list of name mySecondItem
AddItem("myThirdItem"); //Calls AddItem to add an item to the list of name myThirdItem
string[] myArray1 = GetAllItemsAsArray(myList1); //Calls GetAllItemsAsArray to return a string array from myList1
/* foreach (string x in myArray1) //Get each string in myArray1 as x
{
MessageBox.Show(x); //Show x in a MessageBox
} */
}
private void RemoveItem(string name)
{
myList1.RemoveAt(myList1.IndexOf(name)); //Removes an item of name "name" from the list using its index
}
private void AddItem(string name)
{
myList1.Add(name); //Adds an item of name "name" to the list
}
private string[] GetAllItemsAsArray(List<string> list)
{
string[] myArray = new string[list.Count]; //Initialize a new string array of name myArray of length myList1.Count
for (int i = 0; i < list.Count; i++) //Initialize a new int of name i as 0. Continue only if i is less than myList1.Count. Increment i by 1 every time you continue
{
myArray[i] = list[i]; //Set the item index of i where i represents an int of myArray to the corresponding index of int in myList1
}
return myArray; //Return myArray
}
谢谢,
我希望你觉得这有帮助:)