반응형
- where 키워드를 사용하여 T가 구조체인지 클래스인지를 결정할 수 있음
T에 값 형식만 받을 수 있도록 제약조건을 사용
public class TTestA<T> where T : struct { }
TTestA<int> a1 = new TTestA<int>(); // 가능
TTestA<string> a2 = new TTestA<string>(); // 컴파일 에러
T에 참조 형식만 받을 수 있도록 제약조건을 사용
public class TTestB<T> where T : class { } // 참조 형식만
TTestB<int> b1 = new TTestB<int>(); // 컴파일 에러
TTestB<string> b2 = new TTestB<string>(); // 가능
매개변수가 없는 생성자만 생성할 수 있도록 제약조건을 사용
public class TTestC<T> where T : new() { } // 파라미터가 없는 생성자
public class TTestC_1 { }
public class TTestC_2 { public TTestC_2(int i) { } }
TTestC<TTestC_1> c1 = new TTestC<TTestC_1>(); // 가능
TTestC<TTestC_2> c2 = new TTestC<TTestC_2>(); // 컴파일 에러
특정 클래스를 제약조건으로 사용하면 해당 클래스와 해당 클래스에서 파생된 클래스 사용가능
public class TTestD<T> where T : TTestD_1 { }
public class TTestD_1 { }
public class TTestD_2 : TTestD_1 { }
TTestD<TTestD_1> d1 = new TTestD<TTestD_1>(); // 가능
TTestD<TTestD_2> d2 = new TTestD<TTestD_2>(); // 가능
TTestD<TTestC_1> d3 = new TTestD<TTestC_1>(); // 컴파일 에러
반응형
'C#' 카테고리의 다른 글
C# Windows Forms(윈폼) 애플리케이션에서 콘솔 창을 함께 사용(AllocConsole) (0) | 2024.01.07 |
---|---|
C# 스레드(Thread) (0) | 2022.01.10 |
C# 이터레이터(IEnumerable 인터페이스와 yield 키워드) (0) | 2022.01.06 |
C# 익명 형식(Anonymous type) 클래스를 선언하지 않은 인스턴스 (0) | 2022.01.06 |
C# Random 클래스 Next 메서드 (0) | 2022.01.06 |