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.csusing 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.csusing 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.2743338823081The type is System.Double