C# typeof()執行個體詳解

來源:互聯網
上載者:User
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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.