typeof (C# 參考)

用來取得型別的 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 ExampleClass
{
   public int sampleMember;
   public void SampleMethod() {}

   static void Main()
   {
      Type t = typeof(ExampleClass);
      // Alternatively, you could use
      // ExampleClass obj = new ExampleClass();
      // 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:
    Void SampleMethod()
    System.String ToString()
    Boolean Equals(System.Object)
    Int32 GetHashCode()
    System.Type GetType()
    Members:
    Void SampleMethod()
    System.String ToString()
    Boolean Equals(System.Object)
    Int32 GetHashCode()
    System.Type GetType()
    Void .ctor()
    Int32 sampleMember
*/

這個範例會使用 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# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

參考

C# 關鍵字

is (C# 參考)

運算子關鍵字 (C# 參考)

System.Type

概念

C# 程式設計手冊

其他資源

C# 參考