C#의 Type.GetInterfaces() 메서드는 현재 Type이 직접 구현하거나 상속 계층을 통해 물려받은 모든 인터페이스를 배열 형태로 반환하는 리플렉션 API입니다. 이 메서드를 활용하면 특정 타입이 어떤 인터페이스들을 지원하는지 런타임에 동적으로 확인할 수 있어, 플러그인 아키텍처나 타입 검증 로직을 작성할 때 매우 유용합니다.
문법
기본 문법은 다음과 같습니다 −
public abstract Type[] GetInterfaces ();
반환값은 해당 타입이 구현 또는 상속한 모든 인터페이스 정보를 담고 있는 Type[] 배열입니다.
예제 1: float 타입의 인터페이스 조회
다음은 Type.GetInterfaces() 메서드를 사용하여 float 타입이 구현하는 인터페이스 목록을 확인하는 예제입니다 −
using System;
public class Demo {
public static void Main(){
Type type = typeof(float);
Type myInterface = type.GetInterface("IFormattable",true);
Type[] myInterfaces = type.GetInterfaces();
Console.WriteLine("Interface = "+myInterface);
Console.WriteLine("All the Interfaces...");
for (int i = 0; i < myInterfaces.Length; i++)
Console.WriteLine(""+myInterfaces[i]);
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
Interface = System.IFormattable All the Interfaces... System.IComparable System.IFormattable System.IConvertible System.IComparable`1[System.Single] System.IEquatable`1[System.Single]
예제 2: int 타입의 인터페이스 조회
이번에는 int 타입에 대해 동일한 메서드를 적용해 보겠습니다 −
using System;
public class Demo {
public static void Main(){
Type type = typeof(int);
Type myInterface = type.GetInterface("IFormattable");
Type[] myInterfaces = type.GetInterfaces();
Console.WriteLine("Interface = "+myInterface);
Console.WriteLine("All the Interfaces...");
for (int i = 0; i < myInterfaces.Length; i++)
Console.WriteLine(""+myInterfaces[i]);
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
Interface = System.IFormattable All the Interfaces... System.IComparable System.IFormattable System.IConvertible System.IComparable`1[System.Int32] System.IEquatable`1[System.Int32]
참고 사항
Type.GetInterface(string) 메서드는 이름이 일치하는 단일 인터페이스만 반환하며, 두 번째 매개변수를 통해 대소문자 구분 여부(ignoreCase)를 지정할 수 있습니다. 반면 Type.GetInterfaces()는 상속 계층 전체에 걸쳐 구현된 모든 인터페이스를 한 번에 가져오므로, 타입의 인터페이스 구조를 종합적으로 분석하는 데 적합합니다. 두 메서드를 함께 활용하면 더욱 유연한 리플렉션 기반 코드를 작성할 수 있습니다.