본문 바로가기
c#/수업 내용

제너릭(Generics) 클래스 및 메서드

by 이지훈26 2021. 9. 3.

https://docs.microsoft.com/ko-kr/dotnet/csharp/fundamentals/types/generics

 

Generic classes and methods

Learn about generics. Generic types maximize code reuse, type safety, and performance, and are commonly used to create collection classes.

docs.microsoft.com

 

 

*제너릭(Generics) 클래스 및 메서드
-정확한 데이터 형식에 맞게 조정 가능

ArrayList -> List<T>
Hashtable -> Dictionary<TKey, TValue> 를 사용
----------------------------
public class Generic<T>  
{
    public T Field;
}
---------------------------
Generic<string> g = new Generic<string>();
g.Field = "홍길동";    -> 문자열로만 받을 수 있다(정수x)

 

 

using System;
using System.Collections;
using System.Collections.Generic;  //제너릭을 사용하기 위해 추가


namespace Helloworld
{
    class Program
    {

        static void Main(string[] args)
        {
            ArrayList arrayList = new ArrayList();  //컬렉션을 초기화
            arrayList.Add(1);
            arrayList.Add("홍길동");
            arrayList.Add(new Item());
            int num = (int)arrayList[0];  //unboxing
            foreach(object obj in arrayList)
            {
                Console.WriteLine(obj);
            }

            //ArrayList -> List<T>
            //T 형식 매개변수

            List<int> list;      //리스트 변수 선언
            //초기화
            list = new List<int>();
            //값 추가
            list.Add(1);
            list.Add(203);

            int num2 = list[0];
            list[0] = 123;

            
            foreach(int element in list)
            {
                Console.WriteLine(element);
            }
            for(int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
            Console.WriteLine("count: {0}", list.Count);


        }


    }
}