반응형

<제네릭 타입>
: 타입을 미리 정하지 않고, 선언할 때 타입을 지정. T로 주로 표기함.
(ex) List<T> : ArrayList와 달리 선언할 때 타입을 정함 → 다른 타입의 객체를 삽입하려하면 컴파일 오류 발생.
- 제네릭이 될 수 없는 것 : 필드, 속성, 인덱서, 생성자, 이벤트, 종료자
- 타입 parameter(매개변수)와 타입 argument(인수)
public class List<T> -> T : 타입 매개변수
List<string> list = new List<string>(); -> string이 타입 인수
- 제네릭 타입의 초기화 상태 : 개별적으로 초기화, 정적 필드를 독립적으로 가짐.
public class GeneCounter<T>
{
private static int value;
public static void Increment()
{
value++;
}
public static void Display()
{
Console.WriteLine("카운트 : {0}(타입 : {1})",value, typeof(T));
}
}
GeneCounter<string>.Increment(); -> GeneCounter<string> 초기화 수행.
GeneCounter<string>.Display(); -> 카운트 : 1(타입 : System.String) 출력.
GeneCounter<int>.Increment(); -> GeneCounter<int> 초기화 수행.
GeneCounter<int>.Increment();
GeneCounter<int>.Display(); -> 카운트 : 2(타입 : System.Int32) 출력.
class Outer<TO>
{
class Inner<TI>
{
static int value;
}
}
Outer<string>.Inner<string>
Outer<string>.Inner<int>
Outer<int>.Inner<string>
Outer<int>.Inner<int>
-> 독립적인 4개의 타입이 생성, 각각은 고유의 value 필드를 가짐.
<제네릭 애리티(arity)>
: 제네릭 타입이나 제네릭 메서드에서 사용된 타입 매개변수의 개수.
- 메서드 이름과 매개변수 목록이 같아도 애리티가 다르면 서로 다른 메서드.
- 타입 매개변수의 개수를 반드시 달리해야한다는 점에서 오버로드와 차이점이 있음.
enum A {}
class A<T> {}
struct A<T1, T2> {}
interface A<T1, T2, T3> {}
interface A<T4, T5, T6> {} -> 매개변수 개수 같아서 컴파일 타임 에러.
void A<T, T>() {} -> T 중복으로 컴파일 타임 에러.
<default, typeof 연산자>
- default
T ret = default(T); -> 지역 변수를 선언하고 T의 기본값 할당.
- typeof
static void Main(string[] args)
{
PrintType<string>();
}
static void PrintType<T>()
{
Console.WriteLine(typeof(T)); -> System.String 출력.
Console.WriteLine(typeof(List<T>));
-> System.Collections.Generic.List`1[System.String] 출력.
}
반응형
'[Unity] > [C#]' 카테고리의 다른 글
[C#] 캡처(Capture feat. 람다식) (1) | 2022.10.12 |
---|---|
[C#] is, as 연산자 (1) | 2022.10.11 |
[C#] readonly 한정자 (feat.const 한정자) (1) | 2022.10.06 |
[C#] reflection (0) | 2022.10.05 |
[C#] partial 클래스 (0) | 2022.10.04 |