C#에서 특정 타입(Type)이 구현하거나 상속한 모든 인터페이스를 확인해야 하는 경우가 종종 있습니다. 이럴 때 GetInterfaces() 메서드를 활용하면 해당 타입의 모든 인터페이스를 배열 형태로 손쉽게 가져올 수 있습니다. 또한 특정 인터페이스 하나만 조회하고 싶다면 GetInterface() 메서드를 사용하면 됩니다.
주요 메서드 살펴보기
- GetInterface(string name, bool ignoreCase) — 지정한 이름과 일치하는 단일 인터페이스를 반환합니다. 두 번째 매개변수는 이름 비교 시 대소문자를 무시할지 여부를 결정합니다.
- GetInterfaces() — 현재 Type이 구현하거나 상속한 모든 인터페이스를 Type 배열로 반환합니다.
예제 1: float 타입의 인터페이스 조회
먼저 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]
출력 결과에서 확인할 수 있듯이, float 타입은 IComparable, IFormattable, IConvertible과 함께 제네릭 버전인 IComparable<float>, IEquatable<float>까지 총 5개의 인터페이스를 구현하고 있습니다.
예제 2: int 타입의 인터페이스 조회
이번에는 int 타입에 대해 동일한 작업을 수행해 보겠습니다. 이 예제에서는 GetInterface() 호출 시 대소문자 무시 옵션을 생략했다는 점이 첫 번째 예제와 다릅니다.
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.GetInterfaces() 메서드는 리플렉션(Reflection)을 통해 특정 타입이 지원하는 모든 인터페이스 정보를 런타임에 동적으로 확인할 때 매우 유용합니다. 참고로 출력 결과에 나타난 백틱(`) 표기는 제네릭 인터페이스를 의미하며, 예를 들어 System.IComparable`1[System.Int32]는 IComparable<int>를 나타냅니다.