Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# GetInterface() 메서드로 현재 Type의 특정 인터페이스 가져오는 방법

C#에서 현재 Type이 구현하거나 상속받은 특정 인터페이스를 가져오려면 Type.GetInterface() 메서드를 사용합니다. 이 메서드는 지정한 이름과 일치하는 인터페이스를 Type 객체로 반환하며, 일치하는 인터페이스가 존재하지 않으면 null을 반환합니다.

GetInterface() 메서드 기본 사용법

다음 예제는 double 형식에서 IFormattable 인터페이스를 가져오는 방법을 보여줍니다.

예제 1

using System;
public class Demo {
    public static void Main() {
        Type type = typeof(double);
        Type myInterface = type.GetInterface("IFormattable");
        Console.WriteLine("Interface = " + myInterface);
    }
}

출력 결과

Interface = System.IFormattable

대소문자 구분 옵션 활용하기

GetInterface() 메서드는 두 번째 매개변수로 대소문자 무시 여부(ignoreCase)를 지정할 수 있습니다. true를 전달하면 대소문자를 구분하지 않고 인터페이스를 검색하므로, 인터페이스 이름의 정확한 철자를 알지 못하는 경우에도 유용하게 사용할 수 있습니다.

예제 2

using System;
public class Demo {
    public static void Main() {
        Type type = typeof(float);
        Type myInterface = type.GetInterface("IFormattable", true);
        Console.WriteLine("Interface = " + myInterface);
    }
}

출력 결과

Interface = System.IFormattable

정리

Type.GetInterface(string name) 오버로드는 대소문자를 구분하여 인터페이스를 검색하고, Type.GetInterface(string name, bool ignoreCase) 오버로드는 대소문자 구분 여부를 직접 설정할 수 있습니다. 두 방식 모두 현재 형식뿐만 아니라 상속 계층 구조 전체에서 해당 인터페이스를 찾아주며, 리플렉션을 활용해 런타임에 형식의 인터페이스 정보를 동적으로 확인해야 할 때 매우 유용합니다.