Type.GetType 方法

定義

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

多載

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

傳回

Type

目前的 TypeThe current Type.

實作

例外狀況

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

另請參閱

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);
public static Type? GetType (string typeName);
static member GetType : string -> Type
Public Shared Function GetType (typeName As String) As Type

參數

typeName
String

要取得之類型的組件限定名稱。The assembly-qualified name of the type to get. 請參閱 AssemblyQualifiedNameSee 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.

傳回

Type

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

例外狀況

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.

範例

下列範例會抓取的型別 System.Int32 ,並使用該型別物件來顯示的 FullName 屬性 System.Int32The 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

備註

GetType Type 如果您知道可以從取得的元件限定名稱,則可以使用方法取得另一個元件中某個類型的物件 AssemblyQualifiedNameYou 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 導致載入中所指定的元件 typeNameGetType 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. 如果類型在編譯時期在程式已知的元件中,則在 typeof Visual Basic 中使用 c # 或運算子會更有效率 GetTypeIf 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.

注意

如果 typeName 找不到,則呼叫方法會傳回 GetType(String) nullIf typeName cannot be found, the call to the GetType(String) method returns null. 它不會擲回例外狀況。It does not throw an exception. 若要控制是否擲回例外狀況,請呼叫具有參數之方法的多載 GetType throwOnErrorTo 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.AssemblyBuilderAccessThe 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 先訂閱事件並呼叫,然後 GetType 再儲存。To 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.

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

成員類型Member Type StaticStatic 非靜態Non-Static
建構函式Constructor No No
欄位Field No 可以。Yes. 欄位一律會依名稱和簽章進行隱藏。A field is always hide-by-name-and-signature.
Event - 事件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. 依名稱和簽章會考慮簽章的所有部分,包括自訂修飾詞、傳回類型、參數類型、個 sentinel 和非受控呼叫慣例。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. 請參閱 AssemblyQualifiedNameSee AssemblyQualifiedName.

如果 typeName 包含命名空間,但不包含元件名稱,則這個方法只會在呼叫物件的元件中搜尋,並依該順序搜尋 mscorlib.dll/System.Private.CoreLib.dll。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. 支援 common language runtime 的所有編譯器都會發出嵌套類別的簡單名稱,而反映會根據下列慣例,在查詢時建立損壞的名稱。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.

注意

在 .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 物件,並將它傳遞給方法的適當多載,藉以載入類型 LoadYou 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 with 型別名稱或元件限定型別名稱。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 使用元件限定型別名稱時,會 Type 在任何元件中尋找。GetType 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. 例如,反映會 Tuple and 2 從泛型方法 Tuple(Of T)Tuple(Of T0, T1) 在 Visual c # 中的 Visual Basic 或 Tuple<T> 和元組 \<T0, T1> 傳回損壞的名稱1元組。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. Dictionary<TKey,TValue> MyType 具有類型之索引鍵的有 String 可能會以下列方式表示: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. 例如, Dictionary<TKey,TValue> MyType 具有類型之索引鍵的 fromMyAssembly.dll, 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]]")  

注意

只有當元件限定類型出現在類型參數清單中時,才可以用括弧括住。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. nullable ' 1 [system.object]" 表示。For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

注意

在 c #、c + + 和 Visual Basic 中,您也可以使用類型運算子取得可為 null 的類型。In C#, C++, and Visual Basic you can also get nullable types using type operators. 例如,可為 null 的 Boolean 型別是由 typeof(Nullable<bool>) c #、 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]")
的非受控指標 MyTypeAn unmanaged pointer to MyType Type.GetType("MyType*")
指向指標的非受控指標 MyTypeAn unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
的 managed 指標或參考 MyTypeA managed pointer or reference to MyType 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")
下限為0的一維陣列A 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]]")

另請參閱

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);
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

參數

typeName
String

要取得之類型的組件限定名稱。The assembly-qualified name of the type to get. 請參閱 AssemblyQualifiedNameSee 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.

傳回

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.

例外狀況

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.

範例

下列範例會抓取的型別 System.Int32 ,並使用該型別物件來顯示的 FullName 屬性 System.Int32The 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

備註

GetType Type 如果您知道可以從取得的元件限定名稱,則可以使用方法取得另一個元件中某個類型的物件 AssemblyQualifiedNameYou 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 導致載入中所指定的元件 typeNameGetType 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. 如果類型在編譯時期在程式已知的元件中,則在 typeof Visual Basic 中使用 c # 或運算子會更有效率 GetTypeIf 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.AssemblyBuilderAccessThe 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 先訂閱事件並呼叫,然後 GetType 再儲存。To 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參數會指定找不到類型時所發生的情況,也會隱藏某些其他例外狀況,如例外狀況一節中所述。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. 無論的值為何,都會擲回某些例外狀況 throwOnErrorSome exceptions are thrown regardless of the value of throwOnError. 例如,如果找到類型但無法載入,即使為,也會擲回 TypeLoadException throwOnError falseFor example, if the type is found but cannot be loaded, a TypeLoadException is thrown even if throwOnError is false.

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

成員類型Member Type StaticStatic 非靜態Non-Static
建構函式Constructor No No
欄位Field No 可以。Yes. 欄位一律會依名稱和簽章進行隱藏。A field is always hide-by-name-and-signature.
Event - 事件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. 依名稱和簽章會考慮簽章的所有部分,包括自訂修飾詞、傳回類型、參數類型、個 sentinel 和非受控呼叫慣例。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. 請參閱 AssemblyQualifiedNameSee AssemblyQualifiedName.

如果 typeName 包含命名空間,但不包含元件名稱,則這個方法只會在呼叫物件的元件中搜尋,並依該順序搜尋 mscorlib.dll/System.Private.CoreLib.dll。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. 支援 common language runtime 的所有編譯器都會發出嵌套類別的簡單名稱,而反映會根據下列慣例,在查詢時建立損壞的名稱。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.

注意

在 .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 物件,並將它傳遞給方法的適當多載,藉以載入類型 LoadYou 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 with 型別名稱或元件限定型別名稱。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 使用元件限定型別名稱時,會 Type 在任何元件中尋找。GetType 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. 例如,反映會 Tuple and 2 從泛型方法 Tuple(Of T)Tuple(Of T0, T1) 在 Visual c # 中的 Visual Basic 或 Tuple<T> 和元組 \<T0, T1> 傳回損壞的名稱1元組。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. Dictionary<TKey,TValue> MyType 具有類型之索引鍵的有 String 可能會以下列方式表示: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. 例如, Dictionary<TKey,TValue> MyType 從 MyAssembly.dll 的,具有類型的索引鍵 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]]")  

注意

只有當元件限定類型出現在類型參數清單中時,才可以用括弧括住。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. nullable ' 1 [system.object]" 表示。For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

注意

在 c #、c + + 和 Visual Basic 中,您也可以使用類型運算子取得可為 null 的類型。In C#, C++, and Visual Basic you can also get nullable types using type operators. 例如,可為 null 的 Boolean 型別是由 typeof(Nullable<bool>) c #、 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]")
的非受控指標 MyTypeAn unmanaged pointer to MyType Type.GetType("MyType*")
指向指標的非受控指標 MyTypeAn unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
的 managed 指標或參考 MyTypeA managed pointer or reference to MyType 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")
下限為0的一維陣列A 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]]")

另請參閱

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);
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

參數

typeName
String

要取得之類型的組件限定名稱。The assembly-qualified name of the type to get. 請參閱 AssemblyQualifiedNameSee 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.

傳回

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.

例外狀況

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.

備註

GetType Type 如果您知道可以從取得的元件限定名稱,則可以使用方法取得另一個元件中某個類型的物件 AssemblyQualifiedNameYou 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 導致載入中所指定的元件 typeNameGetType 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. 如果類型在編譯時期在程式已知的元件中,則在 typeof Visual Basic 中使用 c # 或運算子會更有效率 GetTypeIf 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.AssemblyBuilderAccessThe 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 先訂閱事件並呼叫,然後 GetType 再儲存。To 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參數會指定找不到類型時所發生的情況,也會隱藏某些其他例外狀況,如例外狀況一節中所述。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. 無論的值為何,都會擲回某些例外狀況 throwOnErrorSome exceptions are thrown regardless of the value of throwOnError. 例如,如果找到類型但無法載入,即使為,也會擲回 TypeLoadException throwOnError falseFor example, if the type is found but cannot be loaded, a TypeLoadException is thrown even if throwOnError is false.

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

成員類型Member Type StaticStatic 非靜態Non-Static
建構函式Constructor No No
欄位Field No 可以。Yes. 欄位一律會依名稱和簽章進行隱藏。A field is always hide-by-name-and-signature.
Event - 事件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. 依名稱和簽章會考慮簽章的所有部分,包括自訂修飾詞、傳回類型、參數類型、個 sentinel 和非受控呼叫慣例。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. 請參閱 AssemblyQualifiedNameSee AssemblyQualifiedName.

如果 typeName 包含命名空間,但不包含元件名稱,則這個方法只會在呼叫物件的元件中搜尋,並依該順序搜尋 mscorlib.dll/System.Private.CoreLib.dll。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. 支援 common language runtime 的所有編譯器都會發出嵌套類別的簡單名稱,而反映會根據下列慣例,在查詢時建立損壞的名稱。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.

注意

在 .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 物件,並將它傳遞給方法的適當多載,藉以載入類型 LoadYou 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 with 型別名稱或元件限定型別名稱。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 使用元件限定型別名稱時,會 Type 在任何元件中尋找。GetType 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. 例如,反映會 Tuple and 2 從泛型方法 Tuple(Of T)Tuple(Of T0, T1) 在 Visual c # 中的 Visual Basic 或 Tuple<T> 和元組 \<T0, T1> 傳回損壞的名稱1元組。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. Dictionary<TKey,TValue> MyType 具有類型之索引鍵的有 String 可能會以下列方式表示: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. 例如, Dictionary<TKey,TValue> MyType 從 MyAssembly.dll 的,具有類型的索引鍵 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]]")  

注意

只有當元件限定類型出現在類型參數清單中時,才可以用括弧括住。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. nullable ' 1 [system.object]" 表示。For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

注意

在 c #、c + + 和 Visual Basic 中,您也可以使用類型運算子取得可為 null 的類型。In C#, C++, and Visual Basic you can also get nullable types using type operators. 例如,可為 null 的 Boolean 型別是由 typeof(Nullable<bool>) c #、 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]")
的非受控指標 MyTypeAn unmanaged pointer to MyType Type.GetType("MyType*")
指向指標的非受控指標 MyTypeAn unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
的 managed 指標或參考 MyTypeA managed pointer or reference to MyType 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")
下限為0的一維陣列A 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]]")

另請參閱

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);
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

參數

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.

傳回

Type

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

例外狀況

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.

備註

此方法的使用案例,以及和參數的詳細資料, assemblyResolver typeResolver 可以在方法多載中找到 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.

注意

如果 typeName 找不到,則呼叫方法會傳回 GetType(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. 若要控制是否擲回例外狀況,請呼叫具有參數之方法的多載 GetType throwOnErrorTo 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)false 針對和參數指定的 throwOnError 相同 ignoreCaseCalling 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);
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

參數

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.

傳回

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.

例外狀況

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.

備註

此方法的使用案例,以及和參數的詳細資料, assemblyResolver typeResolver 可以在方法多載中找到 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)false 針對參數指定的相同 ignoreCaseCalling 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);
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

參數

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.

傳回

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.

例外狀況

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.

備註

使用這個方法多載和其相關聯的多載 (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.

  • 傳回 System.Type 不是由 common language runtime (CLR) 所建立的子類別。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.

注意

如果您不熟悉元件限定型別名稱的概念,請參閱 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/System.Private.CoreLib.dll 或目前執行中元件的內容中解析,或者,您可以選擇性地在參數中提供元件 typeResolverUnqualified 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:

  • 如果方法來自 assemblyResolver typeResolver 未知或不受信任的呼叫端,請不要將方法傳遞給或。Do 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.

    警告

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

  • 如果您省略 assemblyResolver and/or 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.

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

  • 這個方法不會攔截和擲回的例外狀況 assemblyResolver typeResolverThis 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 會接收物件,此物件是由剖析所包含的字串元件名稱所產生 typeNameThe 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. 如果 assemblyResolver 提供,此 GetType 方法不會執行標準探查; 在這種情況下,您必須確定您 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 傳回 nulltypeResolver 則不會呼叫,也不會進行進一步的處理; 此外,如果 throwOnErrortrueFileNotFoundException 則會擲回。If assemblyResolver returns null, typeResolver is not called and no further processing occurs; additionally, if throwOnError is true, a FileNotFoundException is thrown.

如果 AssemblyName 傳遞給的 assemblyResolver 是部分名稱,則其中一或多個部分是 nullIf 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 屬性(property)、 CultureInfo 屬性(property)和 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 指定元件名稱, typeResolver 一律會呼叫。If typeName does not specify an assembly name, typeResolver is always called. 如果 typeName 指定元件名稱, typeResolver 只有在成功解析元件名稱時,才會呼叫。If typeName specifies an assembly name, typeResolver is called only when the assembly name is successfully resolved. 如果 assemblyResolver 或標準元件探查傳回 nulltypeResolver 則不會呼叫。If assemblyResolver or standard assembly probing returns null, typeResolver is not called.

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

  • 要搜尋的元件, null 如果 typeName 不包含元件名稱,則為。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 傳回 null throwOnError ,而且為 true ,這個 GetType TypeLoadException 多載會擲回。If 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.

assemblyResolver您提供的和組合 typeResolver 必須能夠解析此遞迴的所有層級。The combination of assemblyResolver and typeResolver that you provide must be capable of resolving all levels of this recursion. 例如,假設您提供 assemblyResolver 控制載入的 MyAssemblyFor example, suppose you supply an assemblyResolver that controls the loading of MyAssembly. 假設您想要 Dictionary<string, MyType> Dictionary(Of String, MyType) 在 Visual Basic) 中解析泛型型別 (。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 ,因為它會接收 null Dictionary<TKey,TValue>StringYour typeResolver must be able handle either an assembly or null, because it will receive null for Dictionary<TKey,TValue> and String. 它可以藉由呼叫接受字串之方法的多載來處理該情況 GetType ,因為這兩個不合格的型別名稱都在 mscorlib.dll/System.Private.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 ,第一個泛型引數型別是 YourType ,from YourAssemblyNow 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/System.Private.CoreLib.dll 也不是目前執行的元件,所以您無法在 YourType 沒有元件限定名稱的情況下解析。Because 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. null MyAssembly 它現在會使用提供的物件執行元件載入,而不是傳回以外的元件 AssemblyNameInstead 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 ,則必須將 escape 字元加在方括弧前面,如下所示: 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.

注意

具有這類特殊字元的名稱無法在 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 ,則必須移除 escape 字元。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

下表匯總了 assemblyResolvertypeResolver 和預設名稱解析之間的互動,以及中類型名稱和元件名稱的所有組合 typeNameThe 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、assemblytype, assembly nullnull nullnull 相當於呼叫方法多載 Type.GetType(String, Boolean, Boolean)Equivalent to calling the Type.GetType(String, Boolean, Boolean) method overload.
type、assemblytype, assembly 提供provided nullnull assemblyResolver 傳回元件,或在 null 無法解析元件時傳回。assemblyResolver 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、assemblytype, 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、assemblytype, assembly 提供provided 提供provided assemblyResolver 傳回元件,或在 null 無法解析元件時傳回。assemblyResolver 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.
型別type null,提供null, provided nullnull 相當於呼叫方法多載 Type.GetType(String, Boolean, Boolean)Equivalent to calling the Type.GetType(String, Boolean, Boolean) method overload. 由於未提供元件名稱,因此只會搜尋 mscorlib.dll/System.Private.CoreLib.dll 和目前執行中的元件。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.
型別type null,提供null, provided 提供provided typeResolver 呼叫,並且 null 針對元件傳遞。typeResolver 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 null,提供null, provided null,提供null, 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.

適用於