배열을 매개 변수로 전달(C# 프로그래밍 가이드)
업데이트: 2007년 11월
메서드에 매개 변수로 배열을 전달할 수 있습니다. 배열은 참조 형식이므로 메서드에서 요소의 값을 변경할 수 있습니다.
1차원 배열을 매개 변수로 전달
초기화된 1차원 배열을 메서드에 전달할 수 있습니다. 예를 들면 다음과 같습니다.
PrintArray(theArray);
위 코드에서 호출되는 메서드는 다음과 같이 정의할 수 있습니다.
void PrintArray(int[] arr)
{
// method code
}
또한 한 단계로 새 배열을 초기화하여 전달할 수 있습니다. 예를 들어, 다음과 같습니다.
PrintArray(new int[] { 1, 3, 5, 7, 9 });
예제
다음 예제에서는 문자열 배열을 초기화하여 배열의 요소를 출력하는 PrintArray 메서드에 매개 변수로 전달합니다.
class ArrayClass
{
static void PrintArray(string[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : "");
}
System.Console.WriteLine();
}
static void Main()
{
// Declare and initialize an array:
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
// Pass the array as a parameter:
PrintArray(weekDays);
}
}
// Output: Sun Mon Tue Wed Thu Fri Sat
다음 예제에서는 2차원 배열을 초기화한 다음 배열의 요소를 표시하는 PrintArray 메서드에 전달합니다.
class ArrayClass2D
{
static void PrintArray(int[,] arr)
{
// Display the array elements:
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 2; j++)
{
System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);
}
}
}
static void Main()
{
// Pass the array as a parameter:
PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
Element(0,0)=1
Element(0,1)=2
Element(1,0)=3
Element(1,1)=4
Element(2,0)=5
Element(2,1)=6
Element(3,0)=7
Element(3,1)=8
*/
다차원 배열을 매개 변수로 전달
초기화된 다차원 배열을 메서드에 전달할 수 있습니다. 예를 들어 theArray가 2차원 배열인 경우에는 다음과 같습니다.
PrintArray(theArray);
위 코드에서 호출되는 메서드는 다음과 같이 정의할 수 있습니다.
void PrintArray(int[,] arr)
{
// method code
}
또한 한 단계로 새 배열을 초기화하여 전달할 수 있습니다. 예를 들어, 다음과 같습니다.
PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();