이 모두 length
가 0
에 동일했다 length
의 길이로 정의하고, 그 길이는 IDE가 선으로 프로젝트 라인을 컴파일하기 때문에 당신이 그것을 변경하지 않는 한 항상 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
}
감사합니다,
난 당신이되기를 바랍니다 :)이 도움이
정보 주셔서 감사합니다! 확실히 여기에서 뭔가를 배우십시오 – 0070