20 제네릭

vencott·2021년 6월 2일
0

C#

목록 보기
20/32

제네릭 타입에서는 int, float, double 같은 타입을 확정하지 않고 데이터 타입 자체를 타입 파라미터로 받아들이도록 클래스를 정의

제네릭 타입을 사용할 때는 클래스명과 함께 구체적인 데이터 타입을 지정

일부 상이한 데이터 타입 때문에 여러 클래스를 따로 만들 필요가 없다

클래스 외에도 인터페이스나 메서드에 적용 가능

같은 타입 파라미터를 붙여 구현

class MyStack<T>
{
    T[] _elements;
    int pos = 0;

    public MyStack()
    {
        _elements = new T[100];
    }

    public void Push(T element)
    {
        _elements[++pos] = element;
    }

    public T Pop()
    {
        return _elements[pos--];
    }
}

MyStack<int> numberStack = new MyStack<int>();
MyStack<string> nameStack = new MyStack<string>();

.NET Generic 클래스

.NET Framework에는 많은 제네릭 클래스들이 있는데, 특히 System.Collections.Generic 네임스페이스에 있는 모든 자료구조 클래스들은 제네릭 타입

List<string> nameList = new List<string>();
nameList.Add("홍길동");
nameList.Add("이태백");

Dictionary<string, int> dic = new Dictionary<string, int>();
dic["길동"] = 100;
dic["태백"] = 90;

제네릭 타입 제약(Type Constraint)

타입 파라미터에 where T : [제약조건]의 형식으로 조건을 지정할 수 있다

// Value 타입
class MyClass<T> where T : struct 

// Reference 타입
class MyClass<T> where T : class

// 디폴트 생성자를 가져야 함
class MyClass<T> where T : new() 

// MyBase의 파생클래스이어야 함
class MyClass<T> where T : MyBase

// IComparable 인터페이스를 가져야 함
class MyClass<T> where T : IComparable

// 복잡한 제약들
class EmployeeList<T> where T : Employee,
   IEmployee, IComparable<T>, new()
{
}

// 복수 타입 파라미터 제약
class MyClass<T, U> 
    where T : class 
    where U : struct
{
}

출처: http://www.csharpstudy.com/

profile
Backend Developer

0개의 댓글