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);
}

GenericArrayTest.zip
0.01MB

728x90
반응형

'Program Language > C#' 카테고리의 다른 글

[C#] ref 키워드, 참조  (0) 2023.02.16
[C#] out 매개 변수 한정자  (0) 2023.02.16
[C#] 구조체와 클래스  (0) 2023.02.16
[C#] abstract class  (0) 2023.02.16
[C#] OCX에 포인터 데이터 넘기기  (0) 2022.10.26