myArray1
とはどちらも の長さでmyArray2
定義されていたため、 IDE はプロジェクトを 1 行ずつコンパイルするため、変更しない限り、それらの長さは常に同じになります。length
length
0
0
ただし、配列の長さを変更したい場合は、サイズを変更する配列のArray.Resize<T>(ref T[] array, int newSize)
場所と、配列の新しい長さを使用できます。array
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
}
ありがとう、
これがお役に立てば幸いです:)