2012-12-06 5 views
0

을 사용하는 방법 안에 있습니다. 이것은 간단한 질문이지만 하루 종일 괴롭 히고있었습니다. 메서드 내에서 변수를 통해 배열의 길이를 설정하려고합니다 (setLength). 그러나 내가 setLength 메서드를 호출 한 후, 내 배열의 길이는 여전히 0으로 설정되어 있지 않습니다. 메서드를 호출 할 때 5로 설정되지 않았습니까 setLength?세트 배열 길이는 C#

C# 코드 조각 :

class myProject 
{ 
    public static int length = 0; 
    public static string[] myArray1 = new string[length]; 
    public static string[] myArray2 = new string[length]; 

public static void setLength() 
{ 
    length = 5; 
} 

public static void process() 
{ 
    setLength(); 

    for(int i=0; i<length; i++) 
    { 
     .....code for my array 
    } 
} 

답변

6

당신은 새로운 배열을 생성해야합니다.

public static void setLength() 
{ 
    length = 5; 
    myArray1 = new string[length]; 
} 

임의로 길이를 변경할 수는 없습니다. C# 배열은이를 지원하지 않습니다.

는 가변 길이 구조를 사용하려면, 내가 배열의 크기는 당신의 길이 변수의 시간에 개체가 구성되어를 사용하여 설정하는 List<string>

5

을 사용하는 것이 좋습니다 것입니다. 배열에는 가변적 인 관계가 없습니다. 크기는 한 번 설정되고 이후 고정됩니다.

크기가 변하는 배열을 원하면 List < string>과 같은 콜렉션 유형을 사용하십시오. myArray1myArray2 이후

+0

정보 주셔서 감사합니다! 확실히 여기에서 뭔가를 배우십시오 – 0070

2

이 모두 length0에 동일했다 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 
} 

감사합니다,
난 당신이되기를 바랍니다 :)이 도움이

+0

'Array.Resize'는 오해의 소지가 있습니다. 배열의 크기는 변경되지 않고 새로운 배열을 만들고이를 동일한 변수에 할당합니다. 그것은 새로운 배열을 직접 만드는 것과 다른 점이 없으므로 코드를 아주 작게 저장할 수 있습니다. – Servy

+0

@Servy [맞습니다] (http://msdn.microsoft.com/en-us/library/bb348051.aspx)!'Array.Resize'를 사용하면 이전 배열 항목을 이전 배열에서 새로운 배열로 복사 할 때 이전 배열 항목을 버리지 않습니다. 그런 다음 이전 배열을 새 배열로 바꿉니다. 좋은 하루 되세요 :) –

1

당신은 클래스 선언에서 배열의 크기를 initalize에서 초기화되지 않은 무엇을해야 setLength 메소드 이전 답변 상태의 문제는 배열을 초기화하면 크기를 조정하는 데 비용이 많이 드는 작업이라는 것입니다. 이것이 당신이 한 번 이상하고있는 무언가가 될 경우 List<string>을 사용하여 조사해야합니다.

class myProject 
{ 
    public static int length = 0; 
    public static string[] myArray1; 
    public static string[] myArray2; 

    public static void setLength(int value) 
    { 
     myArray1 = new string[value]; 
     myArray2 = new string[value]; 
    } 

    public static void process() 
    { 
     length = 5; 
     setLength(length); 

     for(int i=0; i<length; i++) 
     { 
     .....code for my array 
     } 
    } 
} 
+0

기술적으로 배열의 크기를 조정할 수 없으며 새 배열 만 만들 수 있습니다. – Servy

+0

@Servy 그 이유는 그것이 ** 비싸 ** 언급하고 내 예제에서는 배열의 크기를 조정하지 않습니다. 나는 크기가 알려질 때까지 초기화를 연기하고있다. –

+0

배열의 크기를 조정하는 것은 단지 비싸지는 않지만 불가능합니다. 이전 배열의 모든 항목이 포함 된 새롭고 큰 배열을 다시 만들면 크기가 조정되지 않고 다시 만들어집니다. 그것은 중요한 차이입니다. – Servy