typeof(C#)

보기 전환:
ScriptFree
C# 언어 참조
typeof(C# 참조)

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

System.Type type = typeof(int);
설명

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

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

typeof 연산자는 열린 제네릭 형식에도 사용할 수 있습니다. 형식 매개 변수가 둘 이상인 형식을 지정할 때는 적절한 수의 쉼표를 사용해야 합니다. typeof 연산자는 오버로드되지 않습니다.

예제

// cs_operator_typeof.cs
using System;
using System.Reflection;

public class SampleClass
{
   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:");
      MethodInfo[] methodInfo = t.GetMethods();

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

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

      foreach (MemberInfo mInfo in memberInfo)
         Console.WriteLine(mInfo.ToString());
   }
}

출력

Methods:
Void SampleMethod()
System.Type GetType()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
Members:
Void SampleMethod()
System.Type GetType()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
Void .ctor()
Int32 sampleMember

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

// cs_operator_typeof2.cs
using System;
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()
      );
   }
}

출력

Area = 28.2743338823081
The type is System.Double
C# 언어 사양

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

  • 7.5.11 typeof 연산자

참고 항목

참조

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

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조