Type.GetType Method

Definition

取得代表指定類型的 Type 物件。Gets a Type object that represents the specified type.

Overloads

GetType()

取得目前的 TypeGets the current Type.

GetType(String)

取得具有指定名稱的 Type,執行區分大小寫的搜尋。Gets the Type with the specified name, performing a case-sensitive search.

GetType(String, Boolean)

取得具有指定名稱的 Type,執行區分大小寫的搜尋,並設定找不到該類型時,是否應擲回例外狀況。Gets the Type with the specified name, performing a case-sensitive search and specifying whether to throw an exception if the type is not found.

GetType(String, Boolean, Boolean)

取得具有指定名稱的 Type,指定找不到類型時是否要擲回例外狀況,以及是否要執行區分大小寫的搜尋。Gets the Type with the specified name, specifying whether to throw an exception if the type is not found and whether to perform a case-sensitive search.

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>)

取得具有指定名稱的類型,並選擇性提供自訂方法來解析組件和類型。Gets the type with the specified name, optionally providing custom methods to resolve the assembly and the type.

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean)

取得具有指定名稱的類型,指定找不到類型時是否擲回例外狀況,同時選擇性提供自訂方法來解析組件和類型。Gets the type with the specified name, specifying whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean)

取得具有指定名稱的類型,指定是否執行區分大小寫的搜尋以及找不到類型時是否擲回例外狀況,同時選擇性提供自訂方法來解析組件和類型。Gets the type with the specified name, specifying whether to perform a case-sensitive search and whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

GetType()

取得目前的 TypeGets the current Type.

public:
 Type ^ GetType();
public:
 virtual Type ^ GetType();
public Type GetType ();
override this.GetType : unit -> Type
Public Function GetType () As Type

Returns

Type

目前的 TypeThe current Type.

Implements

Exceptions

叫用類別初始設定式並擲回例外狀況。A class initializer is invoked and throws an exception.

See also

GetType(String)

取得具有指定名稱的 Type,執行區分大小寫的搜尋。Gets the Type with the specified name, performing a case-sensitive search.

public:
 static Type ^ GetType(System::String ^ typeName);
public static Type GetType (string typeName);
static member GetType : string -> Type
Public Shared Function GetType (typeName As String) As Type

Parameters

typeName
String

要取得之類型的組件限定名稱。The assembly-qualified name of the type to get. 請參閱<AssemblyQualifiedName>。See AssemblyQualifiedName. 如果此類型位在目前執行的組件或 mscorlib.dll/System.Private.CoreLib.dll 中,則此類型就能提供本身命名空間限定的類型名稱。If the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

Returns

Type

具有指定名稱的類型 (如有找到),否則為 nullThe type with the specified name, if found; otherwise, null.

Exceptions

typeNamenulltypeName is null.

叫用類別初始設定式並擲回例外狀況。A class initializer is invoked and throws an exception.

typeName 代表的泛型類型以指標類型、ByRef 類型或 Void 做為其中一個類型引數。typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-或--or- typeName 代表的泛型類型具有不正確的類型引數數目。typeName represents a generic type that has an incorrect number of type arguments.

-或--or- typeName 代表泛型類型,其中一個類型引數不符合對應類型參數的條件約束。typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

typeName 代表 TypedReference 的陣列。typeName represents an array of TypedReference.

適用於 Windows 市集應用程式的 .NET 或是可攜式類別庫中,改為攔截基底類別例外狀況IOExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, IOException, instead.

找到組件或其相依性的其中一個,但無法載入。The assembly or one of its dependencies was found, but could not be loaded.

組件或組件的其中一個相依性無效。The assembly or one of its dependencies is not valid.

-或--or-

目前載入的通用語言執行平台是 2.0 版或更新的版本,但用來編譯組件的卻是更新的版本。Version 2.0 or later of the common language runtime is currently loaded, and the assembly was compiled with a later version.

Examples

下列範例會抓取 System.Int32 的類型,並使用該類型物件來顯示 System.Int32FullName 屬性。The following example retrieves the type of System.Int32 and uses that type object to display the FullName property of System.Int32.

using namespace System;

int main()
{
   try {
      // Get the type of a specified class.
      Type^ myType1 = Type::GetType( "System.Int32" );
      Console::WriteLine( "The full name is {0}.\n", myType1->FullName );
   }
   catch ( TypeLoadException^ e ) {
       Console::WriteLine("{0}: Unable to load type System.Int32",
                          e->GetType()->Name);
   }

   try {
      // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
      Type^ myType2 = Type::GetType( "NoneSuch", true );
      Console::WriteLine( "The full name is {0}.", myType2->FullName );
   }
   catch ( TypeLoadException^ e ) {
       Console::WriteLine("{0}: Unable to load type NoneSuch",
                          e->GetType()->Name);
   }

}
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
using System;

class Example
{
     public static void Main()
     {
         try {
             // Get the type of a specified class.
             Type myType1 = Type.GetType("System.Int32");
             Console.WriteLine("The full name is {0}.\n", myType1.FullName);
         }
         catch (TypeLoadException e)
         {
            Console.WriteLine("{0}: Unable to load type System.Int32", e.GetType().Name);
         }

         try {
             // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
             Type myType2 = Type.GetType("NoneSuch", true);
             Console.WriteLine("The full name is {0}.", myType2.FullName);
         }
         catch(TypeLoadException e) {
            Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name);
         }
     }
}
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
Class Example
     Public Shared Sub Main()
         Try
             ' Get the type of the specified class.
             Dim myType1 As Type = Type.GetType("System.Int32")
             Console.WriteLine("The full name is {0}.", myType1.FullName)
         Catch e As TypeLoadException
             Console.WriteLine("{0}: Unable to load type System.Int32",
                               e.GetType().Name)
         End Try

         Console.WriteLine()

         Try
             ' Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
             Dim myType2 As Type = Type.GetType("NoneSuch", True)
             Console.WriteLine("The full name is {0}.", myType2.FullName)
         Catch e As TypeLoadException
             Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name)
         End Try
     End Sub
End Class
' The example displays the following output:
'       The full name is System.Int32.
'
'       TypeLoadException: Unable to load type NoneSuch

Remarks

如果您知道它的元件限定名稱(可以從 AssemblyQualifiedName取得),您可以使用 GetType 方法來取得另一個元件中類型的 Type 物件。You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType 會導致載入 typeName中指定的元件。GetType causes loading of the assembly specified in typeName. 您也可以使用 Assembly.Load 方法載入元件,然後使用 Assembly.GetTypeAssembly.GetTypes 方法來取得 Type 物件。You can also load an assembly using the Assembly.Load method, and then use the Assembly.GetType or Assembly.GetTypes method to get Type objects. 如果類型是在編譯時期已知于您程式中的元件,使用中C# typeof 或 Visual Basic 中的 GetType 運算子會更有效率。If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

Note

如果找不到 typeNameGetType(String) 方法的呼叫會傳回 nullIf typeName cannot be found, the call to the GetType(String) method returns null. 它不會擲回例外狀況。It does not throw an exception. 若要控制是否擲回例外狀況,請呼叫具有 throwOnError 參數之 GetType 方法的多載。To control whether an exception is thrown, call an overload of the GetType method that has a throwOnError parameter.

GetType 僅適用于從磁片載入的元件。GetType only works on assemblies loaded from disk. 如果您呼叫 GetType 來查詢使用 System.Reflection.Emit 服務定義的動態元件中所定義的類型,可能會有不一致的行為。If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. 其行為取決於動態元件是否為持續性,也就是使用 RunAndSaveSave System.Reflection.Emit.AssemblyBuilderAccess 列舉的存取模式所建立的。The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. 如果動態元件是持續性的,而且在呼叫 GetType 之前已寫入磁片,則載入器會在磁片上尋找已儲存的元件、載入該元件,並從該元件抓取類型。If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. 如果在呼叫 GetType 時,元件尚未儲存到磁片中,此方法會傳回 nullIf the assembly has not been saved to disk when GetType is called, the method returns null. GetType 不了解暫時性動態元件;因此,呼叫 GetType 來抓取暫時性動態元件中的型別,會傳回 nullGetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

若要在動態模組上使用 GetType,請訂閱 AppDomain.AssemblyResolve 事件,並在儲存前呼叫 GetTypeTo use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. 否則,您會在記憶體中取得元件的兩個複本。Otherwise, you will get two copies of the assembly in memory.

下表顯示當在類型上反映時,Get 方法傳回的基類成員。The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

成員類型Member Type 靜態Static 非靜態Non-Static
建構函式Constructor No No
欄位Field No 是。Yes. 欄位一律會依名稱和簽章隱藏。A field is always hide-by-name-and-signature.
事件Event 不適用Not applicable 一般類型系統規則是,繼承與實作為屬性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反映會將屬性視為逐名稱和簽章。Reflection treats properties as hide-by-name-and-signature. 請參閱下面的注2。See note 2 below.
方法Method No 是。Yes. 方法(虛擬和非虛擬)可以依名稱或逐名稱和簽章來隱藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
巢狀型別Nested Type No No
屬性Property 不適用Not applicable 一般類型系統規則是,繼承與實作為屬性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反映會將屬性視為逐名稱和簽章。Reflection treats properties as hide-by-name-and-signature. 請參閱下面的注2。See note 2 below.
  1. [逐名稱] 和 [簽章] 會考慮簽章的所有部分,包括自訂修飾詞、傳回類型、參數類型、sentinels 和非受控呼叫慣例。Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. 這是二進位比較。This is a binary comparison.

  2. 針對反映,屬性和事件是依名稱和簽章來隱藏。For reflection, properties and events are hide-by-name-and-signature. 如果您在基類中具有具有 get 和 set 存取子的屬性,但衍生類別只有 get 存取子,則衍生類別屬性會隱藏基類屬性,而且您將無法存取基類上的 setter。If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. 自訂屬性不是一般型別系統的一部分。Custom attributes are not part of the common type system.

除非已將陣列或 COM 類型載入至可用類別的資料表,否則不會搜尋它們。Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.

typeName 可以是其命名空間所限定的類型名稱,或是包含元件名稱規格的元件限定名稱。typeName can be the type name qualified by its namespace or an assembly-qualified name that includes an assembly name specification. 請參閱<AssemblyQualifiedName>。See AssemblyQualifiedName.

如果 typeName 包括命名空間,但不包含元件名稱,則這個方法只會以該順序搜尋呼叫物件的元件和 mscorlib.dll/CoreLib。If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and mscorlib.dll/System.Private.CoreLib.dll, in that order. 如果 typeName 具有部分或完整元件名稱的完整限定,這個方法會在指定的元件中搜尋。If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. 如果元件具有強式名稱,則需要完整的元件名稱。If the assembly has a strong name, a complete assembly name is required.

AssemblyQualifiedName 屬性會傳回完整的類型名稱,包括巢狀型別、元件名稱和泛型型別引數。The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and generic type arguments. 所有支援通用語言執行平臺的編譯器都會發出嵌套類別的簡單名稱,而反映會根據下列慣例,在查詢時建立已損壞的名稱。All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

Note

在 .NET Framework 版本2.0 中,處理器架構會新增至元件識別,並可指定為元件名稱字串的一部分。In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. 例如,"ProcessorArchitecture = msil"。For example, "ProcessorArchitecture=msil". 不過,基於相容性的考慮,它不會包含在 AssemblyQualifiedName 屬性所傳回的字串中。However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. 您也可以藉由建立 AssemblyName 物件,並將它傳遞給 Load 方法的適當多載,來載入類型。You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. 然後,您可以使用 Assembly.GetType 方法,從元件載入類型。You can then use the Assembly.GetType method to load types from the assembly. 另請參閱 AssemblyName.ProcessorArchitectureSee also AssemblyName.ProcessorArchitecture.

分隔符號Delimiter 意義Meaning
反斜線 (\)Backslash (\) Escape 字元。Escape character.
倒引號(')Backtick (`) 在一或多個代表類型參數數目的數位(位於泛型型別名稱的結尾)。Precedes one or more digits representing the number of type parameters, located at the end of the name of a generic type.
方括弧([])Brackets ([]) 將泛型型別引數清單括住于結構化的泛型型別;在類型引數清單中,括住元件限定的類型。Enclose a generic type argument list, for a constructed generic type; within a type argument list, enclose an assembly-qualified type.
逗號 (,)Comma (,) 在元件名稱之前。Precedes the Assembly name.
句點(.)Period (.) 表示命名空間識別碼。Denotes namespace identifiers.
加號 (+)Plus sign (+) 在嵌套類別之前。Precedes a nested class.

例如,類別的完整名稱可能如下所示:For example, the fully qualified name for a class might look like this:

TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly  

如果命名空間是 TopNamespace,則字串必須在加號(+)前面加上一個 escape 字元(\),以防止它被解讀為嵌套分隔符號。If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. 反映會發出此字串,如下所示:Reflection emits this string as follows:

TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly  

"+ +" 會變成 "\+\+",而 "\" 會變成 "\\"。A "++" becomes "\+\+", and a "\" becomes "\\".

這個限定名稱可以保存下來,稍後用來載入 TypeThis qualified name can be persisted and later used to load the Type. 若要搜尋和載入 Type,請使用 GetType,其中只有類型名稱或元件限定類型名稱。To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. 只有類型名稱的 GetType 會在呼叫端的元件中尋找 Type,然後在系統元件中尋找。GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. 具有元件限定類型名稱的 GetType 將會尋找任何元件中的 TypeGetType with the assembly qualified type name will look for the Type in any assembly.

類型名稱可能包含尾端字元,表示類型的其他資訊,例如類型是否為參考型別、指標類型或陣列類型。Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. 若要取出不含這些尾端字元的型別名稱,請使用 t.GetElementType().ToString(),其中 t 是型別。To retrieve the type name without these trailing characters, use t.GetElementType().ToString(), where t is the type.

除了元件名稱以外,所有類型名稱元件中的空間都是相關的。Spaces are relevant in all type name components except the assembly name. 在元件名稱中,',' 分隔符號前面的空格是相關的,但在 ',' 分隔符號之後的空格會被忽略。In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.

泛型型別的名稱以倒引號(`)結尾,後面接著代表泛型型別引數數目的數位。The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. 這個名稱重整的目的是要讓編譯器能夠支援名稱相同但類型參數數目不同的泛型型別,且會出現在相同的範圍中。The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope. 例如,反映會傳回 Tuple1and元組的名稱,2 從泛型方法 Tuple(Of T)Tuple(Of T0, T1) 在 Visual Basic 中,或是在視覺效果C#Tuple<T> 和元組\<T0, T1> 中。For example, reflection returns the mangled names Tuple1andTuple2 from the generic methods Tuple(Of T) and Tuple(Of T0, T1) in Visual Basic, or Tuple<T> and Tuple\<T0, T1> in Visual C#.

若為泛型型別,類型引數清單會以方括弧括住,而類型引數則以逗號分隔。For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas. 例如,泛型 Dictionary<TKey,TValue> 有兩個型別參數。For example, a generic Dictionary<TKey,TValue> has two type parameters. 具有類型 String 索引鍵的 MyType Dictionary<TKey,TValue> 可能會以下列方式表示:A Dictionary<TKey,TValue> of MyType with keys of type String might be represented as follows:

System.Collections.Generic.Dictionary`2[System.String,MyType]  

若要在類型引數清單中指定元件限定的類型,請將元件限定的類型括在方括弧內。To specify an assembly-qualified type within a type argument list, enclose the assembly-qualified type within brackets. 否則,分隔元件限定名稱部分的逗號會被視為分隔其他類型引數。Otherwise, the commas that separate the parts of the assembly-qualified name are interpreted as delimiting additional type arguments. 例如,MyType fromMyAssembly 的 Dictionary<TKey,TValue> 具有類型 String的索引鍵,可能會以下列方式指定:For example, a Dictionary<TKey,TValue> of MyType fromMyAssembly.dll, with keys of type String, might be specified as follows:

Type.GetType("System.Collections.Generic.Dictionary`2[System.String,[MyType,MyAssembly]]")  

Note

只有當元件限定的類型出現在類型參數清單中時,才可以用括弧括住。An assembly-qualified type can be enclosed in brackets only when it appears within a type parameter list. 在類型參數清單中,用於搜尋限定和不合格類型之元件的規則,與合格和不合格非泛型型別的規則相同。The rules for searching assemblies for qualified and unqualified types in type parameter lists are the same as the rules for qualified and unqualified nongeneric types.

可為 null 的類型是泛型型別的特殊案例。Nullable types are a special case of generic types. 例如,可為 null 的 Int32 是以 "system.string ' 1 [System.object]" 字串表示。For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

Note

在C#、 C++和 Visual Basic 您也可以使用類型運算子取得可為 null 的類型。In C#, C++, and Visual Basic you can also get nullable types using type operators. 例如,可為 null 的 Boolean 類型是由中的C#typeof(Nullable<bool>)Nullable<Boolean>::typeid 在C++中,以及 Visual Basic 中的 GetType(Nullable(Of Boolean)) 來傳回。For example, the nullable Boolean type is returned by typeof(Nullable<bool>) in C#, by Nullable<Boolean>::typeid in C++, and by GetType(Nullable(Of Boolean)) in Visual Basic.

下表顯示您針對各種類型的 GetType 所使用的語法。The following table shows the syntax you use with GetType for various types.

若要取得To Get 使用Use
可為 null 的 Int32A nullable Int32 Type.GetType("System.Nullable`1[System.Int32]")
MyType 的非受控指標An unmanaged pointer to MyType Type.GetType("MyType*")
指向指標的非受控指標 MyTypeAn unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
MyType 的 managed 指標或參考A managed pointer or reference to MyType Type.GetType("MyType&")第 1 課:建立 Windows Azure 儲存體物件Type.GetType("MyType&")Type.GetType("MyType&"). 請注意,參考與指標不同,僅限一個層級。Note that unlike pointers, references are limited to one level.
父類別和嵌套類別A parent class and a nested class Type.GetType("MyParentClass+MyNestedClass")
一維陣列,其下限為0A one-dimensional array with a lower bound of 0 Type.GetType("MyType[]")
具有不明下限的一維陣列A one-dimensional array with an unknown lower bound Type.GetType("MyType[*]")
N 維陣列An n-dimensional array 括弧內的逗號(,),總計 n-1 次。A comma (,) inside the brackets a total of n-1 times. 例如,System.Object[,,] 代表一個三維 Object 陣列。For example, System.Object[,,] represents a three-dimensional Object array.
一維陣列的陣列An array of one-dimensional arrays Type.GetType("MyType[][]")
具有不明下限的矩形二維陣列A rectangular two-dimensional array with unknown lower bounds Type.GetType("MyType[,]")
具有一個型別引數的泛型型別A generic type with one type argument Type.GetType("MyGenericType`1[MyType]")
具有兩個型別引數的泛型型別A generic type with two type arguments Type.GetType("MyGenericType`2[MyType,AnotherType]")
具有兩個元件限定類型引數的泛型型別A generic type with two assembly-qualified type arguments Type.GetType("MyGenericType`2[[MyType,MyAssembly],[AnotherType,AnotherAssembly]]")
具有元件限定類型引數的元件限定泛型型別An assembly-qualified generic type with an assembly-qualified type argument Type.GetType("MyGenericType`1[[MyType,MyAssembly]],MyGenericTypeAssembly")
泛型型別,其型別引數為具有兩個型別引數的泛型型別A generic type whose type argument is a generic type with two type arguments Type.GetType("MyGenericType`1[AnotherGenericType`2[MyType,AnotherType]]")

See also

GetType(String, Boolean)

取得具有指定名稱的 Type,執行區分大小寫的搜尋,並設定找不到該類型時,是否應擲回例外狀況。Gets the Type with the specified name, performing a case-sensitive search and specifying whether to throw an exception if the type is not found.

public:
 static Type ^ GetType(System::String ^ typeName, bool throwOnError);
public static Type GetType (string typeName, bool throwOnError);
static member GetType : string * bool -> Type
Public Shared Function GetType (typeName As String, throwOnError As Boolean) As Type

Parameters

typeName
String

要取得之類型的組件限定名稱。The assembly-qualified name of the type to get. 請參閱<AssemblyQualifiedName>。See AssemblyQualifiedName. 如果此類型位在目前執行的組件或 mscorlib.dll/System.Private.CoreLib.dll 中,則此類型就能提供本身命名空間限定的類型名稱。If the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

throwOnError
Boolean

true 表示找不到該類型時擲回例外狀況,而 false 則表示傳回 nulltrue to throw an exception if the type cannot be found; false to return null. 指定 false 也會隱藏其他某些例外狀況條件,但並不是全部。Specifying false also suppresses some other exception conditions, but not all of them. 請參閱<例外狀況>一節。See the Exceptions section.

Returns

Type

具有指定名稱的類型。The type with the specified name. 如果找不到該類型,throwOnError 參數會指定是要傳回 null 或是擲回例外狀況。If the type is not found, the throwOnError parameter specifies whether null is returned or an exception is thrown. 在某些情況下,不論 throwOnError 的值為何,都會擲回例外狀況。In some cases, an exception is thrown regardless of the value of throwOnError. 請參閱<例外狀況>一節。See the Exceptions section.

Exceptions

typeNamenulltypeName is null.

叫用類別初始設定式並擲回例外狀況。A class initializer is invoked and throws an exception.

throwOnErrortrue,而且找不到類型。throwOnError is true and the type is not found.

-或--or- throwOnErrortrue,而且 typeName 包含無效字元,例如內嵌的定位字元。throwOnError is true and typeName contains invalid characters, such as an embedded tab. -或--or- throwOnErrortrue,而且 typeName 是空字串。throwOnError is true and typeName is an empty string.

-或--or- throwOnErrortrue,而且 typeName 代表大小無效的陣列類型。throwOnError is true and typeName represents an array type with an invalid size.

-或--or- typeName 代表 TypedReference 的陣列。typeName represents an array of TypedReference.

throwOnErrortrue,而且 typeName 包含無效的語法。throwOnError is true and typeName contains invalid syntax. 例如,"MyType[,*,]"。For example, "MyType[,*,]".

-或--or- typeName 代表的泛型類型以指標類型、ByRef 類型或 Void 做為其中一個類型引數。typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-或--or- typeName 代表的泛型類型具有不正確的類型引數數目。typeName represents a generic type that has an incorrect number of type arguments.

-或--or- typeName 代表泛型類型,其中一個類型引數不符合對應類型參數的條件約束。typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

throwOnErrortrue,而且找不到組件或組件的其中一個相依性。throwOnError is true and the assembly or one of its dependencies was not found.

適用於 Windows 市集應用程式的 .NET 或是可攜式類別庫中,改為攔截基底類別例外狀況IOExceptionIn the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, IOException, instead.

找到組件或其相依性的其中一個,但無法載入。The assembly or one of its dependencies was found, but could not be loaded.

組件或組件的其中一個相依性無效。The assembly or one of its dependencies is not valid.

-或--or-

目前載入的通用語言執行平台是 2.0 版或更新的版本,但用來編譯組件的卻是更新的版本。Version 2.0 or later of the common language runtime is currently loaded, and the assembly was compiled with a later version.

Examples

下列範例會抓取 System.Int32 的類型,並使用該類型物件來顯示 System.Int32FullName 屬性。The following example retrieves the type of System.Int32 and uses that type object to display the FullName property of System.Int32. 如果類型物件參考的元件不存在,則此範例會擲回例外狀況。If a type object refers to an assembly that does not exist, this example throws an exception.

using namespace System;

int main()
{
   try {
      // Get the type of a specified class.
      Type^ myType1 = Type::GetType( "System.Int32" );
      Console::WriteLine( "The full name is {0}.\n", myType1->FullName );
   }
   catch ( TypeLoadException^ e ) {
       Console::WriteLine("{0}: Unable to load type System.Int32",
                          e->GetType()->Name);
   }

   try {
      // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
      Type^ myType2 = Type::GetType( "NoneSuch", true );
      Console::WriteLine( "The full name is {0}.", myType2->FullName );
   }
   catch ( TypeLoadException^ e ) {
       Console::WriteLine("{0}: Unable to load type NoneSuch",
                          e->GetType()->Name);
   }

}
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
using System;

class Example
{
     public static void Main()
     {
         try {
             // Get the type of a specified class.
             Type myType1 = Type.GetType("System.Int32");
             Console.WriteLine("The full name is {0}.\n", myType1.FullName);
         }
         catch (TypeLoadException e)
         {
            Console.WriteLine("{0}: Unable to load type System.Int32", e.GetType().Name);
         }

         try {
             // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
             Type myType2 = Type.GetType("NoneSuch", true);
             Console.WriteLine("The full name is {0}.", myType2.FullName);
         }
         catch(TypeLoadException e) {
            Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name);
         }
     }
}
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
Class Example
     Public Shared Sub Main()
         Try
             ' Get the type of the specified class.
             Dim myType1 As Type = Type.GetType("System.Int32")
             Console.WriteLine("The full name is {0}.", myType1.FullName)
         Catch e As TypeLoadException
             Console.WriteLine("{0}: Unable to load type System.Int32",
                               e.GetType().Name)
         End Try

         Console.WriteLine()

         Try
             ' Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
             Dim myType2 As Type = Type.GetType("NoneSuch", True)
             Console.WriteLine("The full name is {0}.", myType2.FullName)
         Catch e As TypeLoadException
             Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name)
         End Try
     End Sub
End Class
' The example displays the following output:
'       The full name is System.Int32.
'
'       TypeLoadException: Unable to load type NoneSuch

Remarks

如果您知道它的元件限定名稱(可以從 AssemblyQualifiedName取得),您可以使用 GetType 方法來取得另一個元件中類型的 Type 物件。You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType 會導致載入 typeName中指定的元件。GetType causes loading of the assembly specified in typeName. 您也可以使用 Assembly.Load 方法載入元件,然後使用 Assembly.GetTypeAssembly.GetTypes 方法來取得 Type 物件。You can also load an assembly using the Assembly.Load method, and then use the Assembly.GetType or Assembly.GetTypes method to get Type objects. 如果類型是在編譯時期已知于您程式中的元件,使用中C# typeof 或 Visual Basic 中的 GetType 運算子會更有效率。If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

GetType 僅適用于從磁片載入的元件。GetType only works on assemblies loaded from disk. 如果您呼叫 GetType 來查詢使用 System.Reflection.Emit 服務定義的動態元件中所定義的類型,可能會有不一致的行為。If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. 其行為取決於動態元件是否為持續性,也就是使用 RunAndSaveSave System.Reflection.Emit.AssemblyBuilderAccess 列舉的存取模式所建立的。The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. 如果動態元件是持續性的,而且在呼叫 GetType 之前已寫入磁片,則載入器會在磁片上尋找已儲存的元件、載入該元件,並從該元件抓取類型。If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. 如果在呼叫 GetType 時,元件尚未儲存到磁片中,此方法會傳回 nullIf the assembly has not been saved to disk when GetType is called, the method returns null. GetType 不了解暫時性動態元件;因此,呼叫 GetType 來抓取暫時性動態元件中的型別,會傳回 nullGetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

若要在動態模組上使用 GetType,請訂閱 AppDomain.AssemblyResolve 事件,並在儲存前呼叫 GetTypeTo use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. 否則,您會在記憶體中取得元件的兩個複本。Otherwise, you will get two copies of the assembly in memory.

throwOnError 參數會指定找不到類型時所發生的情況,也會隱藏特定的例外狀況條件,如 exception 一節中所述。The throwOnError parameter specifies what happens when the type is not found, and also suppresses certain other exception conditions, as described in the Exceptions section. 不論 throwOnError的值為何,都會擲回一些例外狀況。Some exceptions are thrown regardless of the value of throwOnError. 例如,如果找到類型,但無法載入,則即使 throwOnError false,也會擲回 TypeLoadExceptionFor example, if the type is found but cannot be loaded, a TypeLoadException is thrown even if throwOnError is false.

下表顯示當在類型上反映時,Get 方法傳回的基類成員。The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

成員類型Member Type 靜態Static 非靜態Non-Static
建構函式Constructor No No
欄位Field No 是。Yes. 欄位一律會依名稱和簽章隱藏。A field is always hide-by-name-and-signature.
事件Event 不適用Not applicable 一般類型系統規則是,繼承與實作為屬性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反映會將屬性視為逐名稱和簽章。Reflection treats properties as hide-by-name-and-signature. 請參閱下面的注2。See note 2 below.
方法Method No 是。Yes. 方法(虛擬和非虛擬)可以依名稱或逐名稱和簽章來隱藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
巢狀型別Nested Type No No
屬性Property 不適用Not applicable 一般類型系統規則是,繼承與實作為屬性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反映會將屬性視為逐名稱和簽章。Reflection treats properties as hide-by-name-and-signature. 請參閱下面的注2。See note 2 below.
  1. [逐名稱] 和 [簽章] 會考慮簽章的所有部分,包括自訂修飾詞、傳回類型、參數類型、sentinels 和非受控呼叫慣例。Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. 這是二進位比較。This is a binary comparison.

  2. 針對反映,屬性和事件是依名稱和簽章來隱藏。For reflection, properties and events are hide-by-name-and-signature. 如果您在基類中具有具有 get 和 set 存取子的屬性,但衍生類別只有 get 存取子,則衍生類別屬性會隱藏基類屬性,而且您將無法存取基類上的 setter。If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. 自訂屬性不是一般型別系統的一部分。Custom attributes are not part of the common type system.

除非已將陣列或 COM 類型載入至可用類別的資料表,否則不會搜尋它們。Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.

typeName 可以是其命名空間所限定的類型名稱,或是包含元件名稱規格的元件限定名稱。typeName can be the type name qualified by its namespace or an assembly-qualified name that includes an assembly name specification. 請參閱<AssemblyQualifiedName>。See AssemblyQualifiedName.

如果 typeName 包括命名空間,但不包含元件名稱,則這個方法只會以該順序搜尋呼叫物件的元件和 mscorlib.dll/CoreLib。If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and mscorlib.dll/System.Private.CoreLib.dll, in that order. 如果 typeName 具有部分或完整元件名稱的完整限定,這個方法會在指定的元件中搜尋。If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. 如果元件具有強式名稱,則需要完整的元件名稱。If the assembly has a strong name, a complete assembly name is required.

AssemblyQualifiedName 屬性會傳回完整的類型名稱,包括巢狀型別、元件名稱和泛型引數。The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and generic arguments. 所有支援通用語言執行平臺的編譯器都會發出嵌套類別的簡單名稱,而反映會根據下列慣例,在查詢時建立已損壞的名稱。All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

Note

在 .NET Framework 版本2.0 中,處理器架構會新增至元件識別,並可指定為元件名稱字串的一部分。In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. 例如,"ProcessorArchitecture = msil"。For example, "ProcessorArchitecture=msil". 不過,基於相容性的考慮,它不會包含在 AssemblyQualifiedName 屬性所傳回的字串中。However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. 您也可以藉由建立 AssemblyName 物件,並將它傳遞給 Load 方法的適當多載,來載入類型。You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. 然後,您可以使用 Assembly.GetType 方法,從元件載入類型。You can then use the Assembly.GetType method to load types from the assembly. 另請參閱 AssemblyName.ProcessorArchitectureSee also AssemblyName.ProcessorArchitecture.

分隔符號Delimiter 意義Meaning
反斜線 (\)Backslash (\) Escape 字元。Escape character.
倒引號(')Backtick (`) 在一或多個代表類型參數數目的數位(位於泛型型別名稱的結尾)。Precedes one or more digits representing the number of type parameters, located at the end of the name of a generic type.
方括弧([])Brackets ([]) 將泛型型別引數清單括住于結構化的泛型型別;在類型引數清單中,括住元件限定的類型。Enclose a generic type argument list, for a constructed generic type; within a type argument list, enclose an assembly-qualified type.
逗號 (,)Comma (,) 在元件名稱之前。Precedes the Assembly name.
句點(.)Period (.) 表示命名空間識別碼。Denotes namespace identifiers.
加號 (+)Plus sign (+) 在嵌套類別之前。Precedes a nested class.

例如,類別的完整名稱可能如下所示:For example, the fully qualified name for a class might look like this:

TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly  

如果命名空間是 TopNamespace,則字串必須在加號(+)前面加上一個 escape 字元(\),以防止它被解讀為嵌套分隔符號。If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. 反映會發出此字串,如下所示:Reflection emits this string as follows:

TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly  

"+ +" 會變成 "\+\+",而 "\" 會變成 "\\"。A "++" becomes "\+\+", and a "\" becomes "\\".

這個限定名稱可以保存下來,稍後用來載入 TypeThis qualified name can be persisted and later used to load the Type. 若要搜尋和載入 Type,請使用 GetType,其中只有類型名稱或元件限定類型名稱。To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. 只有類型名稱的 GetType 會在呼叫端的元件中尋找 Type,然後在系統元件中尋找。GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. 具有元件限定類型名稱的 GetType 將會尋找任何元件中的 TypeGetType with the assembly qualified type name will look for the Type in any assembly.

類型名稱可能包含尾端字元,表示類型的其他資訊,例如類型是否為參考型別、指標類型或陣列類型。Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. 若要取出不含這些尾端字元的型別名稱,請使用 t.GetElementType().ToString(),其中 t 是型別。To retrieve the type name without these trailing characters, use t.GetElementType().ToString(), where t is the type.

除了元件名稱以外,所有類型名稱元件中的空間都是相關的。Spaces are relevant in all type name components except the assembly name. 在元件名稱中,',' 分隔符號前面的空格是相關的,但在 ',' 分隔符號之後的空格會被忽略。In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.

泛型型別的名稱以倒引號(`)結尾,後面接著代表泛型型別引數數目的數位。The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. 這個名稱重整的目的是要讓編譯器能夠支援名稱相同但類型參數數目不同的泛型型別,且會出現在相同的範圍中。The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope. 例如,反映會傳回 Tuple1and元組的名稱,2 從泛型方法 Tuple(Of T)Tuple(Of T0, T1) 在 Visual Basic 中,或是在視覺效果C#Tuple<T> 和元組\<T0, T1> 中。For example, reflection returns the mangled names Tuple1andTuple2 from the generic methods Tuple(Of T) and Tuple(Of T0, T1) in Visual Basic, or Tuple<T> and Tuple\<T0, T1> in Visual C#.

若為泛型型別,類型引數清單會以方括弧括住,而類型引數則以逗號分隔。For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas. 例如,泛型 Dictionary<TKey,TValue> 有兩個型別參數。For example, a generic Dictionary<TKey,TValue> has two type parameters. 具有類型 String 索引鍵的 MyType Dictionary<TKey,TValue> 可能會以下列方式表示:A Dictionary<TKey,TValue> of MyType with keys of type String might be represented as follows:

System.Collections.Generic.Dictionary`2[System.String,MyType]  

若要在類型引數清單中指定元件限定的類型,請將元件限定的類型括在方括弧內。To specify an assembly-qualified type within a type argument list, enclose the assembly-qualified type within brackets. 否則,分隔元件限定名稱部分的逗號會被視為分隔其他類型引數。Otherwise, the commas that separate the parts of the assembly-qualified name are interpreted as delimiting additional type arguments. 例如,從 MyAssembly MyTypeDictionary<TKey,TValue>,以及類型 String的索引鍵,可能會以下列方式指定:For example, a Dictionary<TKey,TValue> of MyType from MyAssembly.dll, with keys of type String, might be specified as follows:

Type.GetType("System.Collections.Generic.Dictionary`2[System.String,[MyType,MyAssembly]]")  

Note

只有當元件限定的類型出現在類型參數清單中時,才可以用括弧括住。An assembly-qualified type can be enclosed in brackets only when it appears within a type parameter list. 在類型參數清單中,用於搜尋限定和不合格類型之元件的規則,與合格和不合格非泛型型別的規則相同。The rules for searching assemblies for qualified and unqualified types in type parameter lists are the same as the rules for qualified and unqualified nongeneric types.

可為 null 的類型是泛型型別的特殊案例。Nullable types are a special case of generic types. 例如,可為 null 的 Int32 是以 "system.string ' 1 [System.object]" 字串表示。For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

Note

在C#、 C++和 Visual Basic 您也可以使用類型運算子取得可為 null 的類型。In C#, C++, and Visual Basic you can also get nullable types using type operators. 例如,可為 null 的 Boolean 類型是由中的C#typeof(Nullable<bool>)Nullable<Boolean>::typeid 在C++中,以及 Visual Basic 中的 GetType(Nullable(Of Boolean)) 來傳回。For example, the nullable Boolean type is returned by typeof(Nullable<bool>) in C#, by Nullable<Boolean>::typeid in C++, and by GetType(Nullable(Of Boolean)) in Visual Basic.

下表顯示您針對各種類型的 GetType 所使用的語法。The following table shows the syntax you use with GetType for various types.

若要取得To Get 使用Use
可為 null 的 Int32A nullable Int32 Type.GetType("System.Nullable`1[System.Int32]")
MyType 的非受控指標An unmanaged pointer to MyType Type.GetType("MyType*")
指向指標的非受控指標 MyTypeAn unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
MyType 的 managed 指標或參考A managed pointer or reference to MyType Type.GetType("MyType&")第 1 課:建立 Windows Azure 儲存體物件Type.GetType("MyType&")Type.GetType("MyType&"). 請注意,參考與指標不同,僅限一個層級。Note that unlike pointers, references are limited to one level.
父類別和嵌套類別A parent class and a nested class Type.GetType("MyParentClass+MyNestedClass")
一維陣列,其下限為0A one-dimensional array with a lower bound of 0 Type.GetType("MyArray[]")
具有不明下限的一維陣列A one-dimensional array with an unknown lower bound Type.GetType("MyArray[*]")
N 維陣列An n-dimensional array 括弧內的逗號(,),總計 n-1 次。A comma (,) inside the brackets a total of n-1 times. 例如,System.Object[,,] 代表一個三維 Object 陣列。For example, System.Object[,,] represents a three-dimensional Object array.
二維陣列的陣列A two-dimensional array's array Type.GetType("MyArray[][]")
具有不明下限的矩形二維陣列A rectangular two-dimensional array with unknown lower bounds Type.GetType("MyArray[,]")
具有一個型別引數的泛型型別A generic type with one type argument Type.GetType("MyGenericType`1[MyType]")
具有兩個型別引數的泛型型別A generic type with two type arguments Type.GetType("MyGenericType`2[MyType,AnotherType]")
具有兩個元件限定類型引數的泛型型別A generic type with two assembly-qualified type arguments Type.GetType("MyGenericType`2[[MyType,MyAssembly],[AnotherType,AnotherAssembly]]")
具有元件限定類型引數的元件限定泛型型別An assembly-qualified generic type with an assembly-qualified type argument Type.GetType("MyGenericType`1[[MyType,MyAssembly]],MyGenericTypeAssembly")
泛型型別,其型別引數為具有兩個型別引數的泛型型別A generic type whose type argument is a generic type with two type arguments Type.GetType("MyGenericType`1[AnotherGenericType`2[MyType,AnotherType]]")

See also

GetType(String, Boolean, Boolean)

取得具有指定名稱的 Type,指定找不到類型時是否要擲回例外狀況,以及是否要執行區分大小寫的搜尋。Gets the Type with the specified name, specifying whether to throw an exception if the type is not found and whether to perform a case-sensitive search.

public:
 static Type ^ GetType(System::String ^ typeName, bool throwOnError, bool ignoreCase);
public static Type GetType (string typeName, bool throwOnError, bool ignoreCase);
static member GetType : string * bool * bool -> Type
Public Shared Function GetType (typeName As String, throwOnError As Boolean, ignoreCase As Boolean) As Type

Parameters

typeName
String

要取得之類型的組件限定名稱。The assembly-qualified name of the type to get. 請參閱<AssemblyQualifiedName>。See AssemblyQualifiedName. 如果此類型位在目前執行的組件或 mscorlib.dll/System.Private.CoreLib.dll 中,則此類型就能提供本身命名空間限定的類型名稱。If the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

throwOnError
Boolean

true 表示找不到該類型時擲回例外狀況,而 false 則表示傳回 nulltrue to throw an exception if the type cannot be found; false to return null. 指定 false 也會隱藏其他某些例外狀況條件,但並不是全部。Specifying false also suppresses some other exception conditions, but not all of them. 請參閱<例外狀況>一節。See the Exceptions section.

ignoreCase
Boolean

true 執行不區分大小寫的搜尋,則為 typeName;為 false 執行區分大小寫的搜尋,則為 typeNametrue to perform a case-insensitive search for typeName, false to perform a case-sensitive search for typeName.

Returns

Type

具有指定名稱的類型。The type with the specified name. 如果找不到該類型,throwOnError 參數會指定是要傳回 null 或是擲回例外狀況。If the type is not found, the throwOnError parameter specifies whether null is returned or an exception is thrown. 在某些情況下,不論 throwOnError 的值為何,都會擲回例外狀況。In some cases, an exception is thrown regardless of the value of throwOnError. 請參閱<例外狀況>一節。See the Exceptions section.

Exceptions

typeNamenulltypeName is null.

叫用類別初始設定式並擲回例外狀況。A class initializer is invoked and throws an exception.

throwOnErrortrue,而且找不到類型。throwOnError is true and the type is not found.

-或--or- throwOnErrortrue,而且 typeName 包含無效字元,例如內嵌的定位字元。throwOnError is true and typeName contains invalid characters, such as an embedded tab. -或--or- throwOnErrortrue,而且 typeName 是空字串。throwOnError is true and typeName is an empty string.

-或--or- throwOnErrortrue,而且 typeName 代表大小無效的陣列類型。throwOnError is true and typeName represents an array type with an invalid size.

-或--or- typeName 代表 TypedReference 的陣列。typeName represents an array of TypedReference.

throwOnErrortrue,而且 typeName 包含無效的語法。throwOnError is true and typeName contains invalid syntax. 例如,"MyType[,*,]"。For example, "MyType[,*,]".

-或--or- typeName 代表的泛型類型以指標類型、ByRef 類型或 Void 做為其中一個類型引數。typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-或--or- typeName 代表的泛型類型具有不正確的類型引數數目。typeName represents a generic type that has an incorrect number of type arguments.

-或--or- typeName 代表泛型類型,其中一個類型引數不符合對應類型參數的條件約束。typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

throwOnErrortrue,而且找不到組件或組件的其中一個相依性。throwOnError is true and the assembly or one of its dependencies was not found.

找到組件或其相依性的其中一個,但無法載入。The assembly or one of its dependencies was found, but could not be loaded.

組件或組件的其中一個相依性無效。The assembly or one of its dependencies is not valid.

-或--or-

目前載入的通用語言執行平台是 2.0 版或更新的版本,但用來編譯組件的卻是更新的版本。Version 2.0 or later of the common language runtime is currently loaded, and the assembly was compiled with a later version.

Remarks

如果您知道它的元件限定名稱(可以從 AssemblyQualifiedName取得),您可以使用 GetType 方法來取得另一個元件中類型的 Type 物件。You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType 會導致載入 typeName中指定的元件。GetType causes loading of the assembly specified in typeName. 您也可以使用 Assembly.Load 方法載入元件,然後使用 Assembly.GetTypeAssembly.GetTypes 方法來取得 Type 物件。You can also load an assembly using the Assembly.Load method, and then use the Assembly.GetType or Assembly.GetTypes method to get Type objects. 如果類型是在編譯時期已知于您程式中的元件,使用中C# typeof 或 Visual Basic 中的 GetType 運算子會更有效率。If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

GetType 僅適用于從磁片載入的元件。GetType only works on assemblies loaded from disk. 如果您呼叫 GetType 來查詢使用 System.Reflection.Emit 服務定義的動態元件中所定義的類型,可能會有不一致的行為。If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. 其行為取決於動態元件是否為持續性,也就是使用 RunAndSaveSave System.Reflection.Emit.AssemblyBuilderAccess 列舉的存取模式所建立的。The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. 如果動態元件是持續性的,而且在呼叫 GetType 之前已寫入磁片,則載入器會在磁片上尋找已儲存的元件、載入該元件,並從該元件抓取類型。If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. 如果在呼叫 GetType 時,元件尚未儲存到磁片中,此方法會傳回 nullIf the assembly has not been saved to disk when GetType is called, the method returns null. GetType 不了解暫時性動態元件;因此,呼叫 GetType 來抓取暫時性動態元件中的型別,會傳回 nullGetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

若要在動態模組上使用 GetType,請訂閱 AppDomain.AssemblyResolve 事件,並在儲存前呼叫 GetTypeTo use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. 否則,您會在記憶體中取得元件的兩個複本。Otherwise, you will get two copies of the assembly in memory.

throwOnError 參數會指定找不到類型時所發生的情況,也會隱藏特定的例外狀況條件,如 exception 一節中所述。The throwOnError parameter specifies what happens when the type is not found, and also suppresses certain other exception conditions, as described in the Exceptions section. 不論 throwOnError的值為何,都會擲回一些例外狀況。Some exceptions are thrown regardless of the value of throwOnError. 例如,如果找到類型,但無法載入,則即使 throwOnError false,也會擲回 TypeLoadExceptionFor example, if the type is found but cannot be loaded, a TypeLoadException is thrown even if throwOnError is false.

下表顯示當在類型上反映時,Get 方法傳回的基類成員。The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

成員類型Member Type 靜態Static 非靜態Non-Static
建構函式Constructor No No
欄位Field No 是。Yes. 欄位一律會依名稱和簽章隱藏。A field is always hide-by-name-and-signature.
事件Event 不適用Not applicable 一般類型系統規則是,繼承與實作為屬性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反映會將屬性視為逐名稱和簽章。Reflection treats properties as hide-by-name-and-signature. 請參閱下面的注2。See note 2 below.
方法Method No 是。Yes. 方法(虛擬和非虛擬)可以依名稱或逐名稱和簽章來隱藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
巢狀型別Nested Type No No
屬性Property 不適用Not applicable 一般類型系統規則是,繼承與實作為屬性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反映會將屬性視為逐名稱和簽章。Reflection treats properties as hide-by-name-and-signature. 請參閱下面的注2。See note 2 below.
  1. [逐名稱] 和 [簽章] 會考慮簽章的所有部分,包括自訂修飾詞、傳回類型、參數類型、sentinels 和非受控呼叫慣例。Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. 這是二進位比較。This is a binary comparison.

  2. 針對反映,屬性和事件是依名稱和簽章來隱藏。For reflection, properties and events are hide-by-name-and-signature. 如果您在基類中具有具有 get 和 set 存取子的屬性,但衍生類別只有 get 存取子,則衍生類別屬性會隱藏基類屬性,而且您將無法存取基類上的 setter。If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. 自訂屬性不是一般型別系統的一部分。Custom attributes are not part of the common type system.

除非已將陣列或 COM 類型載入至可用類別的資料表,否則不會搜尋它們。Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.

typeName 可以是其命名空間所限定的類型名稱,或是包含元件名稱規格的元件限定名稱。typeName can be the type name qualified by its namespace or an assembly-qualified name that includes an assembly name specification. 請參閱<AssemblyQualifiedName>。See AssemblyQualifiedName.

如果 typeName 包括命名空間,但不包含元件名稱,則這個方法只會以該順序搜尋呼叫物件的元件和 mscorlib.dll/CoreLib。If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and mscorlib.dll/System.Private.CoreLib.dll, in that order. 如果 typeName 具有部分或完整元件名稱的完整限定,這個方法會在指定的元件中搜尋。If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. 如果元件具有強式名稱,則需要完整的元件名稱。If the assembly has a strong name, a complete assembly name is required.

AssemblyQualifiedName 屬性會傳回完整的類型名稱,包括巢狀型別、元件名稱和類型引數。The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and type arguments. 所有支援通用語言執行平臺的編譯器都會發出嵌套類別的簡單名稱,而反映會根據下列慣例,在查詢時建立已損壞的名稱。All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

Note

在 .NET Framework 版本2.0 中,處理器架構會新增至元件識別,並可指定為元件名稱字串的一部分。In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. 例如,"ProcessorArchitecture = msil"。For example, "ProcessorArchitecture=msil". 不過,基於相容性的考慮,它不會包含在 AssemblyQualifiedName 屬性所傳回的字串中。However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. 您也可以藉由建立 AssemblyName 物件,並將它傳遞給 Load 方法的適當多載,來載入類型。You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. 然後,您可以使用 Assembly.GetType 方法,從元件載入類型。You can then use the Assembly.GetType method to load types from the assembly. 另請參閱 AssemblyName.ProcessorArchitectureSee also AssemblyName.ProcessorArchitecture.

分隔符號Delimiter 意義Meaning
反斜線 (\)Backslash (\) Escape 字元。Escape character.
倒引號(')Backtick (`) 在一或多個代表類型參數數目的數位(位於泛型型別名稱的結尾)。Precedes one or more digits representing the number of type parameters, located at the end of the name of a generic type.
方括弧([])Brackets ([]) 將泛型型別引數清單括住于結構化的泛型型別;在類型引數清單中,括住元件限定的類型。Enclose a generic type argument list, for a constructed generic type; within a type argument list, enclose an assembly-qualified type.
逗號 (,)Comma (,) 在元件名稱之前。Precedes the Assembly name.
句點(.)Period (.) 表示命名空間識別碼。Denotes namespace identifiers.
加號 (+)Plus sign (+) 在嵌套類別之前。Precedes a nested class.

例如,類別的完整名稱可能如下所示:For example, the fully qualified name for a class might look like this:

TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly  

如果命名空間是 TopNamespace,則字串必須在加號(+)前面加上一個 escape 字元(\),以防止它被解讀為嵌套分隔符號。If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. 反映會發出此字串,如下所示:Reflection emits this string as follows:

TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly  

"+ +" 會變成 "\+\+",而 "\" 會變成 "\\"。A "++" becomes "\+\+", and a "\" becomes "\\".

這個限定名稱可以保存下來,稍後用來載入 TypeThis qualified name can be persisted and later used to load the Type. 若要搜尋和載入 Type,請使用 GetType,其中只有類型名稱或元件限定類型名稱。To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. 只有類型名稱的 GetType 會在呼叫端的元件中尋找 Type,然後在系統元件中尋找。GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. 具有元件限定類型名稱的 GetType 將會尋找任何元件中的 TypeGetType with the assembly qualified type name will look for the Type in any assembly.

類型名稱可能包含尾端字元,表示類型的其他資訊,例如類型是否為參考型別、指標類型或陣列類型。Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. 若要取出不含這些尾端字元的型別名稱,請使用 t.GetElementType().ToString(),其中 t 是型別。To retrieve the type name without these trailing characters, use t.GetElementType().ToString(), where t is the type.

除了元件名稱以外,所有類型名稱元件中的空間都是相關的。Spaces are relevant in all type name components except the assembly name. 在元件名稱中,',' 分隔符號前面的空格是相關的,但在 ',' 分隔符號之後的空格會被忽略。In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.

泛型型別的名稱以倒引號(`)結尾,後面接著代表泛型型別引數數目的數位。The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. 這個名稱重整的目的是要讓編譯器能夠支援名稱相同但類型參數數目不同的泛型型別,且會出現在相同的範圍中。The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope. 例如,反映會傳回 Tuple1and元組的名稱,2 從泛型方法 Tuple(Of T)Tuple(Of T0, T1) 在 Visual Basic 中,或是在視覺效果C#Tuple<T> 和元組\<T0, T1> 中。For example, reflection returns the mangled names Tuple1andTuple2 from the generic methods Tuple(Of T) and Tuple(Of T0, T1) in Visual Basic, or Tuple<T> and Tuple\<T0, T1> in Visual C#.

若為泛型型別,類型引數清單會以方括弧括住,而類型引數則以逗號分隔。For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas. 例如,泛型 Dictionary<TKey,TValue> 有兩個型別參數。For example, a generic Dictionary<TKey,TValue> has two type parameters. 具有類型 String 索引鍵的 MyType Dictionary<TKey,TValue> 可能會以下列方式表示:A Dictionary<TKey,TValue> of MyType with keys of type String might be represented as follows:

System.Collections.Generic.Dictionary`2[System.String,MyType]  

若要在類型引數清單中指定元件限定的類型,請將元件限定的類型括在方括弧內。To specify an assembly-qualified type within a type argument list, enclose the assembly-qualified type within brackets. 否則,分隔元件限定名稱部分的逗號會被視為分隔其他類型引數。Otherwise, the commas that separate the parts of the assembly-qualified name are interpreted as delimiting additional type arguments. 例如,從 MyAssembly MyTypeDictionary<TKey,TValue>,以及類型 String的索引鍵,可能會以下列方式指定:For example, a Dictionary<TKey,TValue> of MyType from MyAssembly.dll, with keys of type String, might be specified as follows:

Type.GetType("System.Collections.Generic.Dictionary`2[System.String,[MyType,MyAssembly]]")  

Note

只有當元件限定的類型出現在類型參數清單中時,才可以用括弧括住。An assembly-qualified type can be enclosed in brackets only when it appears within a type parameter list. 在類型參數清單中,用於搜尋限定和不合格類型之元件的規則,與合格和不合格非泛型型別的規則相同。The rules for searching assemblies for qualified and unqualified types in type parameter lists are the same as the rules for qualified and unqualified nongeneric types.

可為 null 的類型是泛型型別的特殊案例。Nullable types are a special case of generic types. 例如,可為 null 的 Int32 是以 "system.string ' 1 [System.object]" 字串表示。For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

Note

在C#、 C++和 Visual Basic 您也可以使用類型運算子取得可為 null 的類型。In C#, C++, and Visual Basic you can also get nullable types using type operators. 例如,可為 null 的 Boolean 類型是由中的C#typeof(Nullable<bool>)Nullable<Boolean>::typeid 在C++中,以及 Visual Basic 中的 GetType(Nullable(Of Boolean)) 來傳回。For example, the nullable Boolean type is returned by typeof(Nullable<bool>) in C#, by Nullable<Boolean>::typeid in C++, and by GetType(Nullable(Of Boolean)) in Visual Basic.

下表顯示您針對各種類型的 GetType 所使用的語法。The following table shows the syntax you use with GetType for various types.

若要取得To Get 使用Use
可為 null 的 Int32A nullable Int32 Type.GetType("System.Nullable`1[System.Int32]")
MyType 的非受控指標An unmanaged pointer to MyType Type.GetType("MyType*")
指向指標的非受控指標 MyTypeAn unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
MyType 的 managed 指標或參考A managed pointer or reference to MyType Type.GetType("MyType&")第 1 課:建立 Windows Azure 儲存體物件Type.GetType("MyType&")Type.GetType("MyType&"). 請注意,參考與指標不同,僅限一個層級。Note that unlike pointers, references are limited to one level.
父類別和嵌套類別A parent class and a nested class Type.GetType("MyParentClass+MyNestedClass")
一維陣列,其下限為0A one-dimensional array with a lower bound of 0 Type.GetType("MyArray[]")
具有不明下限的一維陣列A one-dimensional array with an unknown lower bound Type.GetType("MyArray[*]")
N 維陣列An n-dimensional array 括弧內的逗號(,),總計 n-1 次。A comma (,) inside the brackets a total of n-1 times. 例如,System.Object[,,] 代表一個三維 Object 陣列。For example, System.Object[,,] represents a three-dimensional Object array.
二維陣列的陣列A two-dimensional array's array Type.GetType("MyArray[][]")
具有不明下限的矩形二維陣列A rectangular two-dimensional array with unknown lower bounds Type.GetType("MyArray[,]")
具有一個型別引數的泛型型別A generic type with one type argument Type.GetType("MyGenericType`1[MyType]")
具有兩個型別引數的泛型型別A generic type with two type arguments Type.GetType("MyGenericType`2[MyType,AnotherType]")
具有兩個元件限定類型引數的泛型型別A generic type with two assembly-qualified type arguments Type.GetType("MyGenericType`2[[MyType,MyAssembly],[AnotherType,AnotherAssembly]]")
具有元件限定類型引數的元件限定泛型型別An assembly-qualified generic type with an assembly-qualified type argument Type.GetType("MyGenericType`1[[MyType,MyAssembly]],MyGenericTypeAssembly")
泛型型別,其型別引數為具有兩個型別引數的泛型型別A generic type whose type argument is a generic type with two type arguments Type.GetType("MyGenericType`1[AnotherGenericType`2[MyType,AnotherType]]")

See also

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>)

取得具有指定名稱的類型,並選擇性提供自訂方法來解析組件和類型。Gets the type with the specified name, optionally providing custom methods to resolve the assembly and the type.

public:
 static Type ^ GetType(System::String ^ typeName, Func<System::Reflection::AssemblyName ^, System::Reflection::Assembly ^> ^ assemblyResolver, Func<System::Reflection::Assembly ^, System::String ^, bool, Type ^> ^ typeResolver);
public static Type GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly> assemblyResolver, Func<System.Reflection.Assembly,string,bool,Type> typeResolver);
static member GetType : string * Func<System.Reflection.AssemblyName, System.Reflection.Assembly> * Func<System.Reflection.Assembly, string, bool, Type> -> Type
Public Shared Function GetType (typeName As String, assemblyResolver As Func(Of AssemblyName, Assembly), typeResolver As Func(Of Assembly, String, Boolean, Type)) As Type

Parameters

typeName
String

要取得之類型的名稱。The name of the type to get. 如果已提供 typeResolver 參數,則類型名稱可為 typeResolver 能解析的任何字串。If the typeResolver parameter is provided, the type name can be any string that typeResolver is capable of resolving. 如果已提供 assemblyResolver 參數或已使用標準類型解析,typeName 就必須是組件限定名稱 (請參閱 AssemblyQualifiedName),除非類型位於目前正在執行的組件或 mscorlib.dll/System.Private.CoreLib.dll 中,在這種情況時,此類型就能提供本身命名空間限定的類型名稱。If the assemblyResolver parameter is provided or if standard type resolution is used, typeName must be an assembly-qualified name (see AssemblyQualifiedName), unless the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, in which case it is sufficient to supply the type name qualified by its namespace.

assemblyResolver
Func<AssemblyName,Assembly>

方法,會找出並傳回 typeName 中指定的組件。A method that locates and returns the assembly that is specified in typeName. 組件名稱做為 assemblyResolver 物件傳遞至 AssemblyNameThe assembly name is passed to assemblyResolver as an AssemblyName object. 如果 typeName 不包含組件名稱,則不會呼叫 assemblyResolverIf typeName does not contain the name of an assembly, assemblyResolver is not called. 如果未提供 assemblyResolver,則會執行標準組件解析。If assemblyResolver is not supplied, standard assembly resolution is performed.

注意:不要從未知或未受信任的呼叫端傳遞方法。Caution Do not pass methods from unknown or untrusted callers. 這樣做可能會提高惡意程式碼的權限。Doing so could result in elevation of privilege for malicious code. 只使用您所提供或熟悉的方法。Use only methods that you provide or that you are familiar with.

typeResolver
Func<Assembly,String,Boolean,Type>

typeName 或標準組件解析傳回的組件,找出並傳回由 assemblyResolver 指定之類型的方法。A method that locates and returns the type that is specified by typeName from the assembly that is returned by assemblyResolver or by standard assembly resolution. 如果未提供任何組件,typeResolver 方法會提供一個組件。If no assembly is provided, the typeResolver method can provide one. 這個方法也使用參數來指定是否執行不區分大小寫的搜尋。會傳遞 false 至該參數。The method also takes a parameter that specifies whether to perform a case-insensitive search; false is passed to that parameter.

注意:不要從未知或未受信任的呼叫端傳遞方法。Caution Do not pass methods from unknown or untrusted callers.

Returns

Type

具有指定名稱的類型;如果找不到類型,則為 nullThe type with the specified name, or null if the type is not found.

Exceptions

typeNamenulltypeName is null.

叫用類別初始設定式並擲回例外狀況。A class initializer is invoked and throws an exception.

typeName 剖析成類型名稱和組件名稱 (例如簡單類型名稱包含未逸出的特殊字元) 時發生錯誤。An error occurs when typeName is parsed into a type name and an assembly name (for example, when the simple type name includes an unescaped special character).

-或--or- typeName 代表的泛型類型以指標類型、ByRef 類型或 Void 做為其中一個類型引數。typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-或--or- typeName 代表的泛型類型具有不正確的類型引數數目。typeName represents a generic type that has an incorrect number of type arguments.

-或--or- typeName 代表泛型類型,其中一個類型引數不符合對應類型參數的條件約束。typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

typeName 代表 TypedReference 的陣列。typeName represents an array of TypedReference.

找到組件或其相依性的其中一個,但無法載入。The assembly or one of its dependencies was found, but could not be loaded.

-或--or- typeName 包含無效組件名稱。typeName contains an invalid assembly name.

-或--or- typeName 是不具類型名稱的有效組件名稱。typeName is a valid assembly name without a type name.

組件或組件的其中一個相依性無效。The assembly or one of its dependencies is not valid.

-或--or-

用以編譯組件的通用語言執行平台,其版本比目前所載入的版本還要更新。The assembly was compiled with a later version of the common language runtime than the version that is currently loaded.

Remarks

此方法的使用案例,以及 assemblyResolvertypeResolver 參數的詳細資料,可以在 GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) 方法多載中找到。Usage scenarios for this method and details about the assemblyResolver and typeResolver parameters can be found in the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload.

Note

如果找不到 typeNameGetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) 方法的呼叫會傳回 nullIf typeName cannot be found, the call to the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) method returns null. 它不會擲回例外狀況。It does not throw an exception. 若要控制是否擲回例外狀況,請呼叫具有 throwOnError 參數之 GetType 方法的多載。To control whether an exception is thrown, call an overload of the GetType method that has a throwOnError parameter.

呼叫這個方法多載等同于呼叫 GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) 方法多載,並指定 throwOnErrorignoreCase 參數的 falseCalling this method overload is the same as calling the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload and specifying false for the throwOnError and ignoreCase parameters.

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean)

取得具有指定名稱的類型,指定找不到類型時是否擲回例外狀況,同時選擇性提供自訂方法來解析組件和類型。Gets the type with the specified name, specifying whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

public:
 static Type ^ GetType(System::String ^ typeName, Func<System::Reflection::AssemblyName ^, System::Reflection::Assembly ^> ^ assemblyResolver, Func<System::Reflection::Assembly ^, System::String ^, bool, Type ^> ^ typeResolver, bool throwOnError);
public static Type GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly> assemblyResolver, Func<System.Reflection.Assembly,string,bool,Type> typeResolver, bool throwOnError);
static member GetType : string * Func<System.Reflection.AssemblyName, System.Reflection.Assembly> * Func<System.Reflection.Assembly, string, bool, Type> * bool -> Type
Public Shared Function GetType (typeName As String, assemblyResolver As Func(Of AssemblyName, Assembly), typeResolver As Func(Of Assembly, String, Boolean, Type), throwOnError As Boolean) As Type

Parameters

typeName
String

要取得之類型的名稱。The name of the type to get. 如果已提供 typeResolver 參數,則類型名稱可為 typeResolver 能解析的任何字串。If the typeResolver parameter is provided, the type name can be any string that typeResolver is capable of resolving. 如果已提供 assemblyResolver 參數或已使用標準類型解析,typeName 就必須是組件限定名稱 (請參閱 AssemblyQualifiedName),除非類型位於目前正在執行的組件或 mscorlib.dll/System.Private.CoreLib.dll 中,在這種情況時,此類型就能提供本身命名空間限定的類型名稱。If the assemblyResolver parameter is provided or if standard type resolution is used, typeName must be an assembly-qualified name (see AssemblyQualifiedName), unless the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, in which case it is sufficient to supply the type name qualified by its namespace.

assemblyResolver
Func<AssemblyName,Assembly>

方法,會找出並傳回 typeName 中指定的組件。A method that locates and returns the assembly that is specified in typeName. 組件名稱做為 assemblyResolver 物件傳遞至 AssemblyNameThe assembly name is passed to assemblyResolver as an AssemblyName object. 如果 typeName 不包含組件名稱,則不會呼叫 assemblyResolverIf typeName does not contain the name of an assembly, assemblyResolver is not called. 如果未提供 assemblyResolver,則會執行標準組件解析。If assemblyResolver is not supplied, standard assembly resolution is performed.

注意:不要從未知或未受信任的呼叫端傳遞方法。Caution Do not pass methods from unknown or untrusted callers. 這樣做可能會提高惡意程式碼的權限。Doing so could result in elevation of privilege for malicious code. 只使用您所提供或熟悉的方法。Use only methods that you provide or that you are familiar with.

typeResolver
Func<Assembly,String,Boolean,Type>

typeName 或標準組件解析傳回的組件,找出並傳回由 assemblyResolver 指定之類型的方法。A method that locates and returns the type that is specified by typeName from the assembly that is returned by assemblyResolver or by standard assembly resolution. 如果未提供任何組件,方法會提供一個組件。If no assembly is provided, the method can provide one. 這個方法也使用參數來指定是否執行不區分大小寫的搜尋。會傳遞 false 至該參數。The method also takes a parameter that specifies whether to perform a case-insensitive search; false is passed to that parameter.

注意:不要從未知或未受信任的呼叫端傳遞方法。Caution Do not pass methods from unknown or untrusted callers.

throwOnError
Boolean

true 表示找不到該類型時擲回例外狀況,而 false 則表示傳回 nulltrue to throw an exception if the type cannot be found; false to return null. 指定 false 也會隱藏其他某些例外狀況條件,但並不是全部。Specifying false also suppresses some other exception conditions, but not all of them. 請參閱<例外狀況>一節。See the Exceptions section.

Returns

Type

具有指定名稱的類型。The type with the specified name. 如果找不到該類型,throwOnError 參數會指定是要傳回 null 或是擲回例外狀況。If the type is not found, the throwOnError parameter specifies whether null is returned or an exception is thrown. 在某些情況下,不論 throwOnError 的值為何,都會擲回例外狀況。In some cases, an exception is thrown regardless of the value of throwOnError. 請參閱<例外狀況>一節。See the Exceptions section.

Exceptions

typeNamenulltypeName is null.

叫用類別初始設定式並擲回例外狀況。A class initializer is invoked and throws an exception.

throwOnErrortrue,而且找不到類型。throwOnError is true and the type is not found.

-或--or- throwOnErrortrue,而且 typeName 包含無效字元,例如內嵌的定位字元。throwOnError is true and typeName contains invalid characters, such as an embedded tab. -或--or- throwOnErrortrue,而且 typeName 是空字串。throwOnError is true and typeName is an empty string.

-或--or- throwOnErrortrue,而且 typeName 代表大小無效的陣列類型。throwOnError is true and typeName represents an array type with an invalid size.

-或--or- typeName 代表 TypedReference 的陣列。typeName represents an array of TypedReference.

typeName 剖析成類型名稱和組件名稱 (例如簡單類型名稱包含未逸出的特殊字元) 時發生錯誤。An error occurs when typeName is parsed into a type name and an assembly name (for example, when the simple type name includes an unescaped special character).

-或--or- throwOnErrortrue,而且 typeName 包含無效語法 (例如 "MyType[,*,]")。throwOnError is true and typeName contains invalid syntax (for example, "MyType[,*,]").

-或--or- typeName 代表的泛型類型以指標類型、ByRef 類型或 Void 做為其中一個類型引數。typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-或--or- typeName 代表的泛型類型具有不正確的類型引數數目。typeName represents a generic type that has an incorrect number of type arguments.

-或--or- typeName 代表泛型類型,其中一個類型引數不符合對應類型參數的條件約束。typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

throwOnErrortrue,而且找不到組件或組件的其中一個相依性。throwOnError is true and the assembly or one of its dependencies was not found.

-或--or- typeName 包含無效組件名稱。typeName contains an invalid assembly name.

-或--or- typeName 是不具類型名稱的有效組件名稱。typeName is a valid assembly name without a type name.

找到組件或其相依性的其中一個,但無法載入。The assembly or one of its dependencies was found, but could not be loaded.

組件或組件的其中一個相依性無效。The assembly or one of its dependencies is not valid.

-或--or-

用以編譯組件的通用語言執行平台,其版本比目前所載入的版本還要更新。The assembly was compiled with a later version of the common language runtime than the version that is currently loaded.

Remarks

此方法的使用案例,以及 assemblyResolvertypeResolver 參數的詳細資料,可以在 GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) 方法多載中找到。Usage scenarios for this method and details about the assemblyResolver and typeResolver parameters can be found in the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload.

呼叫這個方法多載與呼叫 GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) 方法多載,並指定 ignoreCase 參數的 false 相同。Calling this method overload is the same as calling the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload and specifying false for the ignoreCase parameter.

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean)

取得具有指定名稱的類型,指定是否執行區分大小寫的搜尋以及找不到類型時是否擲回例外狀況,同時選擇性提供自訂方法來解析組件和類型。Gets the type with the specified name, specifying whether to perform a case-sensitive search and whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

public:
 static Type ^ GetType(System::String ^ typeName, Func<System::Reflection::AssemblyName ^, System::Reflection::Assembly ^> ^ assemblyResolver, Func<System::Reflection::Assembly ^, System::String ^, bool, Type ^> ^ typeResolver, bool throwOnError, bool ignoreCase);
public static Type GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly> assemblyResolver, Func<System.Reflection.Assembly,string,bool,Type> typeResolver, bool throwOnError, bool ignoreCase);
static member GetType : string * Func<System.Reflection.AssemblyName, System.Reflection.Assembly> * Func<System.Reflection.Assembly, string, bool, Type> * bool * bool -> Type
Public Shared Function GetType (typeName As String, assemblyResolver As Func(Of AssemblyName, Assembly), typeResolver As Func(Of Assembly, String, Boolean, Type), throwOnError As Boolean, ignoreCase As Boolean) As Type

Parameters

typeName
String

要取得之類型的名稱。The name of the type to get. 如果已提供 typeResolver 參數,則類型名稱可為 typeResolver 能解析的任何字串。If the typeResolver parameter is provided, the type name can be any string that typeResolver is capable of resolving. 如果已提供 assemblyResolver 參數或已使用標準類型解析,typeName 就必須是組件限定名稱 (請參閱 AssemblyQualifiedName),除非類型位於目前正在執行的組件或 mscorlib.dll/System.Private.CoreLib.dll 中,在這種情況時,此類型就能提供本身命名空間限定的類型名稱。If the assemblyResolver parameter is provided or if standard type resolution is used, typeName must be an assembly-qualified name (see AssemblyQualifiedName), unless the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, in which case it is sufficient to supply the type name qualified by its namespace.

assemblyResolver
Func<AssemblyName,Assembly>

方法,會找出並傳回 typeName 中指定的組件。A method that locates and returns the assembly that is specified in typeName. 組件名稱做為 assemblyResolver 物件傳遞至 AssemblyNameThe assembly name is passed to assemblyResolver as an AssemblyName object. 如果 typeName 不包含組件名稱,則不會呼叫 assemblyResolverIf typeName does not contain the name of an assembly, assemblyResolver is not called. 如果未提供 assemblyResolver,則會執行標準組件解析。If assemblyResolver is not supplied, standard assembly resolution is performed.

注意:不要從未知或未受信任的呼叫端傳遞方法。Caution Do not pass methods from unknown or untrusted callers. 這樣做可能會提高惡意程式碼的權限。Doing so could result in elevation of privilege for malicious code. 只使用您所提供或熟悉的方法。Use only methods that you provide or that you are familiar with.

typeResolver
Func<Assembly,String,Boolean,Type>

typeName 或標準組件解析傳回的組件,找出並傳回由 assemblyResolver 指定之類型的方法。A method that locates and returns the type that is specified by typeName from the assembly that is returned by assemblyResolver or by standard assembly resolution. 如果未提供任何組件,方法會提供一個組件。If no assembly is provided, the method can provide one. 這個方法也使用參數來指定是否執行不區分大小寫的搜尋。會傳遞 ignoreCase 的值至該參數。The method also takes a parameter that specifies whether to perform a case-insensitive search; the value of ignoreCase is passed to that parameter.

注意:不要從未知或未受信任的呼叫端傳遞方法。Caution Do not pass methods from unknown or untrusted callers.

throwOnError
Boolean

true 表示找不到該類型時擲回例外狀況,而 false 則表示傳回 nulltrue to throw an exception if the type cannot be found; false to return null. 指定 false 也會隱藏其他某些例外狀況條件,但並不是全部。Specifying false also suppresses some other exception conditions, but not all of them. 請參閱<例外狀況>一節。See the Exceptions section.

ignoreCase
Boolean

true 執行不區分大小寫的搜尋,則為 typeName;為 false 執行區分大小寫的搜尋,則為 typeNametrue to perform a case-insensitive search for typeName, false to perform a case-sensitive search for typeName.

Returns

Type

具有指定名稱的類型。The type with the specified name. 如果找不到該類型,throwOnError 參數會指定是要傳回 null 或是擲回例外狀況。If the type is not found, the throwOnError parameter specifies whether null is returned or an exception is thrown. 在某些情況下,不論 throwOnError 的值為何,都會擲回例外狀況。In some cases, an exception is thrown regardless of the value of throwOnError. 請參閱<例外狀況>一節。See the Exceptions section.

Exceptions

typeNamenulltypeName is null.

叫用類別初始設定式並擲回例外狀況。A class initializer is invoked and throws an exception.

throwOnErrortrue,而且找不到類型。throwOnError is true and the type is not found.

-或--or- throwOnErrortrue,而且 typeName 包含無效字元,例如內嵌的定位字元。throwOnError is true and typeName contains invalid characters, such as an embedded tab. -或--or- throwOnErrortrue,而且 typeName 是空字串。throwOnError is true and typeName is an empty string.

-或--or- throwOnErrortrue,而且 typeName 代表大小無效的陣列類型。throwOnError is true and typeName represents an array type with an invalid size.

-或--or- typeName 代表 TypedReference 的陣列。typeName represents an array of TypedReference.

typeName 剖析成類型名稱和組件名稱 (例如簡單類型名稱包含未逸出的特殊字元) 時發生錯誤。An error occurs when typeName is parsed into a type name and an assembly name (for example, when the simple type name includes an unescaped special character).

-或--or- throwOnErrortrue,而且 typeName 包含無效語法 (例如 "MyType[,*,]")。throwOnError is true and typeName contains invalid syntax (for example, "MyType[,*,]").

-或--or- typeName 代表的泛型類型以指標類型、ByRef 類型或 Void 做為其中一個類型引數。typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-或--or- typeName 代表的泛型類型具有不正確的類型引數數目。typeName represents a generic type that has an incorrect number of type arguments.

-或--or- typeName 代表泛型類型,其中一個類型引數不符合對應類型參數的條件約束。typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

throwOnErrortrue,而且找不到組件或組件的其中一個相依性。throwOnError is true and the assembly or one of its dependencies was not found.

找到組件或其相依性的其中一個,但無法載入。The assembly or one of its dependencies was found, but could not be loaded.

-或--or- typeName 包含無效組件名稱。typeName contains an invalid assembly name.

-或--or- typeName 是不具類型名稱的有效組件名稱。typeName is a valid assembly name without a type name.

組件或組件的其中一個相依性無效。The assembly or one of its dependencies is not valid.

-或--or-

用以編譯組件的通用語言執行平台,其版本比目前所載入的版本還要更新。The assembly was compiled with a later version of the common language runtime than the version that is currently loaded.

Remarks

使用這個方法多載和其相關聯的多載(GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>)GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean)),以更有彈性的方式來取代 GetType 方法的預設執行。Use this method overload and its associated overloads (GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) and GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean)) to replace the default implementation of the GetType method with more flexible implementations. 藉由提供您自己的方法來解析類型名稱和包含它們之元件的名稱,您可以執行下列動作:By providing your own methods that resolve type names and the names of the assemblies that contain them, you can do the following:

  • 控制載入類型的元件版本。Control which version of an assembly a type is loaded from.

  • 提供另一個位置,以尋找不包含元件名稱的類型名稱。Provide another place to look for a type name that does not include an assembly name.

  • 使用部分元件名稱載入元件。Load assemblies using partial assembly names.

  • 傳回不是由 common language runtime (CLR)所建立之 System.Type 的子類別。Return subclasses of System.Type that are not created by the common language runtime (CLR).

例如,在版本相容序列化中,此方法可讓您使用部分名稱來搜尋「最適合」元件。For example, in version-tolerant serialization this method enables you to search for a "best fit" assembly by using a partial name. GetType 方法的其他多載需要元件限定的類型名稱,其中包含版本號碼。Other overloads of the GetType method require an assembly-qualified type name, which includes the version number.

類型系統的替代執行可能需要傳回 CLR 不會建立之 System.Type 的子類別。GetType 方法的其他多載所傳回的所有類型都是執行時間類型。Alternate implementations of the type system may need to return subclasses of System.Type that are not created by the CLR; all types that are returned by other overloads of the GetType method are runtime types.

使用注意事項Usage Notes

這個方法多載和其相關聯的多載會將 typeName 剖析成型別的名稱和元件的名稱,然後再解析名稱。This method overload and its associated overloads parse typeName into the name of a type and the name of an assembly, and then resolve the names. 在解析類型名稱之前,會發生元件名稱的解析,因為類型名稱必須在元件的內容中解析。Resolution of the assembly name occurs before resolution of the type name, because a type name must be resolved in the context of an assembly.

Note

如果您不熟悉元件限定類型名稱的概念,請參閱 AssemblyQualifiedName 屬性。If you are unfamiliar with the concept of assembly-qualified type names, see the AssemblyQualifiedName property.

如果 typeName 不是元件限定的名稱,則會略過元件解析。If typeName is not an assembly-qualified name, assembly resolution is skipped. 不合格的類型名稱可以在 mscorlib.dll/CoreLib 或目前執行的元件內容中解析,或者您也可以選擇性地在 typeResolver 參數中提供元件。Unqualified type names can be resolved in the context of mscorlib.dll/System.Private.CoreLib.dll or the currently executing assembly, or you can optionally provide an assembly in the typeResolver parameter. 包含或省略不同名稱解析類型之元件名稱的效果,會顯示為 [混合名稱解析] 區段中的資料表。The effects of including or omitting the assembly name for different kinds of name resolution are displayed as a table in the Mixed Name Resolution section.

一般使用注意事項:General usage notes:

  • 如果方法來自未知或不受信任的呼叫端,請勿傳遞方法來 assemblyResolvertypeResolverDo not pass methods to assemblyResolver or typeResolver if they come from unknown or untrusted callers. 只使用您所提供或熟悉的方法。Use only methods that you provide or that you are familiar with.

    Caution

    使用來自未知或未受信任之呼叫端的方法,可能會導致惡意程式碼的權限提高。Using methods from unknown or untrusted callers could result in elevation of privilege for malicious code.

  • 如果您省略 assemblyResolver 和/或 typeResolver 參數,則 throwOnError 參數的值會傳遞至執行預設解析的方法。If you omit the assemblyResolver and/or typeResolver parameters, the value of the throwOnError parameter is passed to the methods that perform the default resolution.

  • 如果 true``throwOnError,則當 typeResolver 傳回 null時,這個方法會擲回 TypeLoadException,而當 FileNotFoundException 傳回 assemblyResolver 時,則會擲回一個 nullIf throwOnError is true, this method throws a TypeLoadException when typeResolver returns null, and a FileNotFoundException when assemblyResolver returns null.

  • 這個方法不會攔截 assemblyResolvertypeResolver擲回的例外狀況。This method does not catch exceptions thrown by assemblyResolver and typeResolver. 您必須負責解析程式方法所擲回的任何例外狀況。You are responsible for any exceptions that are thrown by the resolver methods.

解析元件Resolving Assemblies

assemblyResolver 方法會接收 AssemblyName 物件,其是藉由剖析包含在 typeName中的字串元件名稱所產生。The assemblyResolver method receives an AssemblyName object, which is produced by parsing the string assembly name that is included in typeName. 如果 typeName 不包含元件名稱,則不會呼叫 assemblyResolver,而且 null 會傳遞至 typeResolverIf typeName does not contain an assembly name, assemblyResolver is not called and null is passed to typeResolver.

如果未提供 assemblyResolver,則會使用標準的元件探查來尋找元件。If assemblyResolver is not supplied, standard assembly probing is used to locate the assembly. 如果提供 assemblyResolverGetType 方法不會執行標準探查;在此情況下,您必須確定您的 assemblyResolver 可以處理您傳遞給它的所有元件。If assemblyResolver is provided, the GetType method does not do standard probing; in that case you must ensure that your assemblyResolver can handle all the assemblies you pass to it.

如果無法解析元件,assemblyResolver 方法應該會傳回 nullThe assemblyResolver method should return null if the assembly cannot be resolved. 如果 assemblyResolver 傳回 null,則不會呼叫 typeResolver,也不會進行進一步的處理。此外,如果 true``throwOnError,則會擲回 FileNotFoundExceptionIf assemblyResolver returns null, typeResolver is not called and no further processing occurs; additionally, if throwOnError is true, a FileNotFoundException is thrown.

如果傳遞至 assemblyResolverAssemblyName 是部分名稱,則會 null其中一個或多個元件。If the AssemblyName that is passed to assemblyResolver is a partial name, one or more of its parts are null. 例如,如果沒有版本,Version 屬性會 nullFor example, if it has no version, the Version property is null. 如果 Version 屬性、CultureInfo 屬性和 GetPublicKeyToken 方法全都傳回 null,則只提供元件的簡單名稱。If the Version property, the CultureInfo property, and the GetPublicKeyToken method all return null, then only the simple name of the assembly was supplied. assemblyResolver 方法可以使用或忽略元件名稱的所有部分。The assemblyResolver method can use or ignore all parts of the assembly name.

不同元件解析選項的效果會顯示為混合名稱解析區段中的資料表,適用于簡單和元件限定的類型名稱。The effects of different assembly resolution options are displayed as a table in the Mixed Name Resolution section, for simple and assembly-qualified type names.

解析類型Resolving Types

如果 typeName 未指定元件名稱,則一律會呼叫 typeResolverIf typeName does not specify an assembly name, typeResolver is always called. 如果 typeName 指定元件名稱,只有在成功解析元件名稱時,才會呼叫 typeResolverIf typeName specifies an assembly name, typeResolver is called only when the assembly name is successfully resolved. 如果 assemblyResolver 或標準元件探查傳回 null,則不會呼叫 typeResolverIf assemblyResolver or standard assembly probing returns null, typeResolver is not called.

typeResolver 方法會接收三個引數:The typeResolver method receives three arguments:

  • 如果 typeName 不包含元件名稱,則為要搜尋或 null 的元件。The assembly to search or null if typeName does not contain an assembly name.

  • 類型的簡單名稱。The simple name of the type. 在巢狀型別的情況下,這是最外層的包含類型。In the case of a nested type, this is the outermost containing type. 在泛型型別的情況下,這是泛型型別的簡單名稱。In the case of a generic type, this is the simple name of the generic type.

  • 如果要忽略類型名稱的大小寫,則為 true 的布林值。A Boolean value that is true if the case of type names is to be ignored.

此實作為決定使用這些引數的方式。The implementation determines the way these arguments are used. 如果 typeResolver 方法無法解析類型,則應該傳回 nullThe typeResolver method should return null if it cannot resolve the type. 如果 typeResolver 傳回 nulltrue``throwOnError,則此 GetType 的多載會擲回 TypeLoadExceptionIf typeResolver returns null and throwOnError is true, this overload of GetType throws a TypeLoadException.

不同類型解析選項的效果會顯示為 [混合名稱解析] 區段中的資料表,適用于簡單和元件限定的類型名稱。The effects of different type resolution options are displayed as a table in the Mixed Name Resolution section, for simple and assembly-qualified type names.

解析巢狀型別Resolving Nested Types

如果 typeName 是巢狀型別,則只會將最外層包含類型的名稱傳遞給 typeResolverIf typeName is a nested type, only the name of the outermost containing type is passed to typeResolver. typeResolver 傳回此類型時,會以遞迴方式呼叫 GetNestedType 方法,直到解析最內層的巢狀型別為止。When typeResolver returns this type, the GetNestedType method is called recursively until the innermost nested type has been resolved.

解析泛型型別Resolving Generic Types

GetType 會以遞迴方式呼叫以解析泛型型別:第一種是解析泛型型別本身,然後解析它的型別引數。The GetType is called recursively to resolve generic types: First to resolve the generic type itself, and then to resolve its type arguments. 如果類型引數是泛型,GetType 會以遞迴方式呼叫以解析其型別引數,依此類推。If a type argument is generic, GetType is called recursively to resolve its type arguments, and so on.

您所提供的 assemblyResolvertypeResolver 組合,必須能夠解析此遞迴的所有層級。The combination of assemblyResolver and typeResolver that you provide must be capable of resolving all levels of this recursion. 例如,假設您提供的 assemblyResolver 可控制 MyAssembly的載入。For example, suppose you supply an assemblyResolver that controls the loading of MyAssembly. 假設您想要解析泛型型別 Dictionary<string, MyType> (Visual Basic 中的Dictionary(Of String, MyType))。Suppose you want to resolve the generic type Dictionary<string, MyType> (Dictionary(Of String, MyType) in Visual Basic). 您可以傳遞下列泛型型別名稱:You might pass the following generic type name:

"System.Collections.Generic.Dictionary`2[System.String,[MyNamespace.MyType, MyAssembly]]"  

請注意,MyType 是唯一的元件限定型別引數。Notice that MyType is the only assembly-qualified type argument. Dictionary<TKey,TValue>String 類別的名稱不是元件限定的。The names of the Dictionary<TKey,TValue> and String classes are not assembly-qualified. 您的 typeResolver 必須能夠處理元件或 null,因為它會接收 Dictionary<TKey,TValue>StringnullYour typeResolver must be able handle either an assembly or null, because it will receive null for Dictionary<TKey,TValue> and String. 它可以藉由呼叫接受字串之 GetType 方法的多載來處理這種情況,因為這兩個不合格的類型名稱都是在 mscorlib.dll/CoreLib .dll 中:It can handle that case by calling an overload of the GetType method that takes a string, because both of the unqualified type names are in mscorlib.dll/System.Private.CoreLib.dll:

Type t = Type.GetType(test,
                      (aName) => aName.Name == "MyAssembly" ?
                          Assembly.LoadFrom(@".\MyPath\v5.0\MyAssembly.dll") : null,
                      (assem, name, ignore) => assem == null ?
                          Type.GetType(name, false, ignore) :
                              assem.GetType(name, false, ignore)
                     );

不會針對字典類型和字串類型呼叫 assemblyResolver 方法,因為這些類型名稱不是元件限定的。The assemblyResolver method is not called for the dictionary type and the string type, because those type names are not assembly-qualified.

現在假設,而不是 System.String,第一個泛型引數類型從 YourAssembly``YourTypeNow suppose that instead of System.String, the first generic argument type is YourType, from YourAssembly:

"System.Collections.Generic.Dictionary`2[[YourNamespace.YourType, YourAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], [MyNamespace.MyType, MyAssembly]]"  

由於此元件既不是 mscorlib.dll/CoreLib,也不是目前正在執行的元件,因此您無法解析不具元件限定名稱的 YourTypeBecause this assembly is neither mscorlib.dll/System.Private.CoreLib.dll nor the currently executing assembly, you cannot resolve YourType without an assembly-qualified name. 因為您的 assemblyResolve 會以遞迴方式呼叫,所以它必須能夠處理這種情況。Because your assemblyResolve will be called recursively, it must be able to handle this case. 它現在會使用所提供的 AssemblyName 物件來執行元件載入,而不是傳回 MyAssembly以外的元件 nullInstead of returning null for assemblies other than MyAssembly, it now performs an assembly load using the supplied AssemblyName object.

Type t2 = Type.GetType(test,
                       (aName) => aName.Name == "MyAssembly" ?
                           Assembly.LoadFrom(@".\MyPath\v5.0\MyAssembly.dll") :
                           Assembly.Load(aName),
                       (assem, name, ignore) => assem == null ?
                           Type.GetType(name, false, ignore) :
                               assem.GetType(name, false, ignore), true
                      );

回到 [使用注意事項]。Back to Usage Notes.

解析具有特殊字元的類型名稱Resolving Type Names with Special Characters

某些字元在元件限定名稱中具有特殊意義。Certain characters have special meanings in assembly-qualified names. 如果簡單類型名稱包含這些字元,則當簡單名稱是元件限定名稱的一部分時,字元會導致剖析錯誤。If a simple type name contains these characters, the characters cause parsing errors when the simple name is part of an assembly-qualified name. 若要避免剖析錯誤,您必須先使用反斜線來轉義特殊字元,才能將元件限定的名稱傳遞給 GetType 方法。To avoid the parsing errors, you must escape the special characters with a backslash before you can pass the assembly-qualified name to the GetType method. 例如,如果類型命名為 Strange]Type,則必須在方括弧前面加入逸出字元,如下所示: Strange\]TypeFor example, if a type is named Strange]Type, the escape character must be added ahead of the square bracket as follows: Strange\]Type.

Note

具有這類特殊字元的名稱無法在 Visual Basic 或C#中建立,但可以使用 Microsoft 中繼語言(MSIL)或發出動態元件來建立。Names with such special characters cannot be created in Visual Basic or C#, but can be created by using Microsoft intermediate language (MSIL) or by emitting dynamic assemblies.

下表顯示型別名稱的特殊字元。The following table shows the special characters for type names.

字元Character 意義Meaning
, (逗號), (comma) 元件限定名稱的分隔符號。Delimiter for assembly-qualified names.
[] (方括弧)[] (square brackets) 作為尾碼配對,表示陣列類型;做為分隔符號組,會括住泛型引數清單和元件限定的名稱。As a suffix pair, indicates an array type; as a delimiter pair, encloses generic argument lists and assembly-qualified names.
& (連字號)& (ampersand) 作為尾碼,表示類型是參考型別。As a suffix, indicates that a type is a reference type.
* (星號)* (asterisk) 作為尾碼,表示類型是指標類型。As a suffix, indicates that a type is a pointer type.
+ (加上)+ (plus) 巢狀型別的分隔符號。Delimiter for nested types.
\ (反斜線)\ (backslash) Escape 字元。Escape character.

AssemblyQualifiedName 之類的屬性會傳回正確的逸出字元串。Properties such as AssemblyQualifiedName return correctly escaped strings. 您必須將正確的已逸出字元串傳遞給 GetType 方法。You must pass correctly escaped strings to the GetType method. 接著,GetType 方法會將正確的轉義名稱傳遞給 typeResolver 和預設的類型解析方法。In turn, the GetType method passes correctly escaped names to typeResolver and to the default type resolution methods. 如果您需要在 typeResolver中比較名稱與未轉義的名稱,則必須移除逸出字元。If you need to compare a name to an unescaped name in typeResolver, you must remove the escape characters.

回到 [使用注意事項]。Back to Usage Notes.

混合名稱解析Mixed Name Resolution

下表摘要說明 typeName中類型名稱和元件名稱的所有組合的 assemblyResolvertypeResolver和預設名稱解析之間的互動:The following table summarizes the interactions between assemblyResolver, typeResolver, and default name resolution, for all combinations of type name and assembly name in typeName:

類型名稱的內容Contents of type name 元件解析程式方法Assembly resolver method 類型解析程式方法Type resolver method 結果Result
類型、元件type, assembly nullnull nullnull 相當於呼叫 Type.GetType(String, Boolean, Boolean) 方法多載。Equivalent to calling the Type.GetType(String, Boolean, Boolean) method overload.
類型、元件type, assembly 給定provided nullnull assemblyResolver 會傳回元件,或在無法解析元件時傳回 nullassemblyResolver returns the assembly or returns null if it cannot resolve the assembly. 如果解析元件,則會使用 Assembly.GetType(String, Boolean, Boolean) 方法多載,從元件載入型別。否則,就不會嘗試解析類型。If the assembly is resolved, the Assembly.GetType(String, Boolean, Boolean) method overload is used to load the type from the assembly; otherwise, there is no attempt to resolve the type.
類型、元件type, assembly nullnull 給定provided 相當於將元件名稱轉換為 AssemblyName 物件,並呼叫 Assembly.Load(AssemblyName) 方法多載來取得元件。Equivalent to converting the assembly name to an AssemblyName object and calling the Assembly.Load(AssemblyName) method overload to get the assembly. 如果已解析元件,則會將它傳遞給 typeResolver。否則,不會呼叫 typeResolver,也不會進一步嘗試解析類型。If the assembly is resolved, it is passed to typeResolver; otherwise, typeResolver is not called and there is no further attempt to resolve the type.
類型、元件type, assembly 給定provided 給定provided assemblyResolver 會傳回元件,或在無法解析元件時傳回 nullassemblyResolver returns the assembly or returns null if it cannot resolve the assembly. 如果已解析元件,則會將它傳遞給 typeResolver。否則,不會呼叫 typeResolver,也不會進一步嘗試解析類型。If the assembly is resolved, it is passed to typeResolver; otherwise, typeResolver is not called and there is no further attempt to resolve the type.
typetype 提供的 nullnull, provided nullnull 相當於呼叫 Type.GetType(String, Boolean, Boolean) 方法多載。Equivalent to calling the Type.GetType(String, Boolean, Boolean) method overload. 因為未提供元件名稱,所以只會搜尋 mscorlib.dll/CoreLib 和目前正在執行的元件。Because the assembly name is not provided, only mscorlib.dll/System.Private.CoreLib.dll and the currently executing assembly are searched. 如果提供 assemblyResolver,則會予以忽略。If assemblyResolver is provided, it is ignored.
typetype 提供的 nullnull, provided 給定provided 呼叫 typeResolver,並為元件傳遞 nulltypeResolver is called, and null is passed for the assembly. typeResolver 可以從任何元件提供類型,包括它為了目的而載入的元件。typeResolver can provide a type from any assembly, including assemblies it loads for the purpose. 如果提供 assemblyResolver,則會予以忽略。If assemblyResolver is provided, it is ignored.
組件 (assembly)assembly 提供的 nullnull, provided 提供的 nullnull, provided 會擲回 FileLoadException,因為元件名稱會剖析為元件限定的型別名稱。A FileLoadException is thrown, because the assembly name is parsed as if it were an assembly-qualified type name. 這會產生不正確元件名稱。This results in an invalid assembly name.

回到:使用方式注意事項解析元件解析類型Back to: Usage Notes, Resolving Assemblies, Resolving Types.

Applies to