C# - where) 복습을 위해 작성하는 글 2023-05-02

rizz·2023년 5월 2일
0

C

목록 보기
14/25

📒 갈무리 - where

📌 where이란?

- 제네릭을 사용할 때, 특정 조건에만 대응되는 데이터 타입이 필요한 경우가 있는데, 이러한 경우에 where 키워드를 사용하여 제약 조건을 추가할 수 있으며, 제약 조건을 만족하지 않는 경우에는 컴파일 에러가 발생하도록 할 수 있다.

 

📌 where 예제

// C#

    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<int> genericObject = new GenericClass<int>();

            // class 형식만 허용.
            GenericClass<Student> genericObject = new GenericClass<Student>();
        }
    }

다중 제약 조건

// C#

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에서 상속

profile
복습하기 위해 쓰는 글

0개의 댓글