反映 (C#)Reflection (C#)

反映提供的物件 (類型為 Type) 可描述組件、模組和類型。Reflection provides objects (of type Type) that describe assemblies, modules and types. 您可以使用反映來動態建立類型的執行個體、將類型繫結至現有的物件,或從現有的物件取得類型,並叫用其方法或存取其欄位及屬性。You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. 如果您在程式碼中使用屬性,則反映可讓您存取它們。If you are using attributes in your code, reflection enables you to access them. 如需詳細資訊,請參閱屬性For more information, see Attributes.

以下簡單反映範例使用 Object 基底類別的所有類型所繼承的靜態方法 GetType 來取得變數的類型︰Here's a simple example of reflection using the static method GetType - inherited by all types from the Object base class - to obtain the type of a variable:

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

輸出為:The output is:

System.Int32

下列範例使用反映以取得所載入組件的完整名稱。The following example uses reflection to obtain the full name of the loaded assembly.

// Using Reflection to get information of an Assembly:  
System.Reflection.Assembly info = typeof(System.Int32).Assembly;  
System.Console.WriteLine(info);  

輸出為:The output is:

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

注意

C# 關鍵字 protectedinternal 在 IL 中沒有任何意義,而且不會用於反映 API 中。The C# keywords protected and internal have no meaning in IL and are not used in the reflection APIs. IL 中的對應詞彙是「系列」和「組件」。The corresponding terms in IL are Family and Assembly. 若要使用反映來識別 internal 方法,請使用 IsAssembly 屬性。To identify an internal method using reflection, use the IsAssembly property. 若要識別 protected internal 方法,請使用 IsFamilyOrAssemblyTo identify a protected internal method, use the IsFamilyOrAssembly.

反映概觀Reflection Overview

反映在下列情況下十分有用:Reflection is useful in the following situations:

如需詳細資訊:For more information:

另請參閱See also