Program Language/C#
[C#] Generic Array
야곰야곰+책벌레
2023. 2. 16. 15:24
728x90
반응형
Generic Array는 C++의 template랑 비슷한 형태를 하고 있다. <T>에서 T는 변수의 형식이 된다.
static void ProcessItems<T>(IList<T> coll)
{
// IsReadOnly returns True for the array and False for the List.
System.Console.WriteLine("IsReadOnly returns {0} for this collection.", coll.IsReadOnly);
// The following statement causes a run-time exception for the
// array, but not for the List.
//coll.RemoveAt(4);
foreach (T item in coll)
{
System.Console.Write(item.ToString() + " ");
}
System.Console.WriteLine();
}
매개변수가 되는 coll은 어떤 타입이 될지는 모르지만, 가지고 있는 개수만큼 콘솔에 표시된다.
일반적인 int 배열이나 List를 이용하여 매개 변수를 전달하여도 정상 동작한다.
static void Main(string[] args)
{
int[] arr = { 0, 1, 2, 3, 4 };
List<int> list = new List<int>();
for (int x = 5; x < 10; x++)
{
list.Add(x);
}
ProcessItems<int>(arr);
ProcessItems<int>(list);
}
728x90
반응형