📒 갈무리 - where
📌 where이란?
- 제네릭을 사용할 때, 특정 조건에만 대응되는 데이터 타입이 필요한 경우가 있는데, 이러한 경우에 where 키워드를 사용하여 제약 조건을 추가할 수 있으며, 제약 조건을 만족하지 않는 경우에는 컴파일 에러가 발생하도록 할 수 있다.
📌 where 예제
class GenericClass<T> where T : class
{
public T objectStudent { get; set; }
}
class Student
{
private string name;
private int korean;
private int eng;
private int math;
}
class Program
{
static void Main(string[] args)
{
GenericClass<Student> genericObject = new GenericClass<Student>();
}
}
다중 제약 조건
class Student<T, U>
where T : class
where U : struct
{
}
📌 where 제약 조건 종류
struct : null을 허용하지 않는 값 형식
class : 참조 형식
null 허용 참조 형식 사용 시 class? 제약 조건을 사용(C# 8.0 이상)
new() : 매개변수가 없는 public 생성자가 있어야 하고, 다른 제약조건과 함께 사용되는 경우 new() 제약 조건을 마지막에 지정해야 함
notnull : null이 아닌 형식(C# 8.0 이상)
unmanaged : null이 아닌 비관리형 형식
<base class name> : 지정된 기본 클래스이거나 이 클래스에서 파생된 유형
<interface name> : 지정된 기본 인터페이스이거나 이 인터페이스에서 파생된 유형
U : 추상 클래스 또는 일반 클래스가 될 수 있고, T는 U에서 상속