typeof(C# 참조)

업데이트: 2007년 11월

형식에 대한 System.Type 개체를 얻는 데 사용됩니다. typeof 식의 형식은 다음과 같습니다.

System.Type type = typeof(int);

설명

식의 런타임 형식을 얻으려면 다음 예제와 같이 .NET Framework 메서드 GetType을 사용합니다.

int i = 0;
System.Type type = i.GetType();

typeof 연산자는 오버로드되지 않습니다.

typeof 연산자는 열린 제네릭 형식에도 사용할 수 있습니다. 형식 매개 변수가 둘 이상인 형식을 지정할 때는 적절한 수의 쉼표를 사용해야 합니다. 다음 예제에서는 메서드의 반환 형식이 제네릭 IEnumerable<T>인지 여부를 확인하는 방법을 보여 줍니다. 메서드는 MethodInfo 형식의 인스턴스라고 가정합니다.

string s = method.ReturnType.GetInterface
    (typeof(System.Collections.Generic.IEnumerable<>).FullName

예제

public class SampleClass2
{
   public int sampleMember;
   public void SampleMethod() {}

   static void Main()
   {
      Type t = typeof(SampleClass);
      // Alternatively, you could use
      // SampleClass obj = new SampleClass();
      // Type t = obj.GetType();

      Console.WriteLine("Methods:");
      System.Reflection.MethodInfo[] methodInfo = t.GetMethods();

      foreach (System.Reflection.MethodInfo mInfo in methodInfo)
         Console.WriteLine(mInfo.ToString());

      Console.WriteLine("Members:");
      System.Reflection.MemberInfo[] memberInfo = t.GetMembers();

      foreach (System.Reflection.MemberInfo mInfo in memberInfo)
         Console.WriteLine(mInfo.ToString());
   }
}
/*
 Output:
    Methods:
    System.Type GetType()
    System.String ToString()
    Boolean Equals(System.Object)
    Int32 GetHashCode()
    Members:
    System.Type GetType()
    System.String ToString()
    Boolean Equals(System.Object)
    Int32 GetHashCode()
    Void .ctor()
    Void .ctor(Int32, System.String)
    System.String name
    Int32 id
*/

이 샘플에서는 숫자 계산의 결과를 포함하는 데 사용되는 형식을 확인하기 위해 GetType 메서드를 사용합니다. 이 형식은 계산 결과를 저장하는 데 필요한 요구 사항에 따라 달라집니다.

class GetTypeTest
{
    static void Main()
    {
        int radius = 3;
        Console.WriteLine("Area = {0}", radius * radius * Math.PI);
        Console.WriteLine("The type is {0}",
                          (radius * radius * Math.PI).GetType()
        );
    }
}
/*
Output:
Area = 28.2743338823081
The type is System.Double
*/

C# 언어 사양

자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.

  • 7.5.11 typeof 연산자

참고 항목

개념

C# 프로그래밍 가이드

참조

C# 키워드

is(C# 참조)

연산자 키워드(C# 참조)

기타 리소스

C# 참조