본문 바로가기

Language/C#

Generalization

Generalization(일반화)


Generalization는 서로 다른 개념에서 공통점을 찾는것이다.

'A', 'B', 'C'는 다른 단어지만 '영어'라는 공통점을 가지며

int, float, string은 다른 type이지만 '변수'라는 공통점을 가진다.

위처럼 어떤 개념을 포괄하는 공통된 개념을 찾아 서로 다른 개념을 하나로 묶어주는것이다.



    
void print(int A)
{
    Console.WriteLine(A);
}
void print(float B)
{
    Console.WriteLine(B);
}
void print(string C)
{
    Console.WriteLine(C);
}

//위 3개 method를 generalization한 method
void print(T value)
{
    Console.WriteLine(value);
}

/*
해당함수는 이렇게 호출한다
int age = 27;
float height = 180.2f;
string name = "Papa";

print(age);
print(height);
print(name);
*/



Method뿐만 아니라 Class도 genralization할 수 있다.



    
class List_int
{
    public int[] arr;
}
class List_float
{
    public float[] arr;
}
class List_string
{
    public string[] arr;
}

//위 3개 class를 generalization한 class
class List
{
    public T[] arr;
}

/*
사용법은 다음과 같다.

List list1 = new List();
list1.arr[0] = 10;
List list2 = new List();
list2.arr[0] = 2.2f;
List list3 = new List();
list3.arr[0] = "generalization";
*/



T변수 제약조건


T는 모든type이 가능했으나 이를 "Where T : 제약조건" 으로 특정 type으로 제약할 수도 있다.



    
class List where T : class // T의 type은 class여야 한다.
{
// ...
}
class Print where U : struct // U의 type은 값(int, float 등등..)이어야 한다.
{
// ...
}

/*
여러 제약 조건

Where T : new( ) // T는 매개변수가 없는 생성자를 가진 type이어야 한다.
where T : class name // T는 지정한 class type이거나 이를 상속받는 class이어야 한다.
where T : interface name // T는 interface를 상속받는 class이어야 한다.
where T : U // T는 형식매개변수 U의 type이거나 이를 상속받는 class이어야 한다.
/*



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

강한참조 / 약한참조(WeakReference)  (0) 2019.03.13
.NET Reflection  (0) 2019.03.08
Boxing / UnBoxing  (0) 2019.03.06
Collection의 성능문제 / Generic Collection  (0) 2019.03.06
C# 제네릭  (0) 2019.03.06