Share via


反映 (C# 和 Visual Basic)

反映 (Reflection) 會提供 Type 型別的物件,用來描述組件、模組和型別。 您可以使用反映來動態建立型別的執行個體、將型別繫結至現有物件,或從現有物件取得型別,並叫用其方法或存取其欄位和屬性。 如果您在程式碼中使用屬性,反映可讓您存取這些屬性。 如需詳細資訊,請參閱使用屬性擴充中繼資料

下面是一個簡單的反映範例,這個範例使用 Object 基底類別所有型別繼承的靜態方法 GetType,來取得變數的型別:

' Using GetType to obtain type information:
Dim i As Integer = 42
Dim type As System.Type = i.GetType()
System.Console.WriteLine(type)
// Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

輸出如下:

System.Int32

下列範例會使用反映來取得載入之組件的完整名稱。

' Using Reflection to get information from an Assembly:
Dim info As System.Reflection.Assembly = GetType(System.Int32).Assembly
System.Console.WriteLine(info)
// Using Reflection to get information from an Assembly:
System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);

輸出如下:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

注意事項注意事項

C# 關鍵字 protected 和 internal 在 IL 中沒有意義,而且不會在反映 API 中使用。IL 中對應的術語為「家族」(Family) 和「組件」(Assembly)。若要使用反映識別 internal 方法,請使用 IsAssembly 屬性。若要識別 protected internal 方法,請使用 IsFamilyOrAssembly

反映概觀

在下列狀況中,反映會十分有用:

相關章節

如需詳細資訊,請參閱下列主題:

請參閱

概念

C# 程式設計手冊

其他資源

Visual Basic 程式設計手冊

應用程式定義域 (C# 和 Visual Basic)

Common Language Runtime 中的組件