Type.GetType Type.GetType Type.GetType Type.GetType Method

定义

获取表示指定类型的 Type 对象。Gets a Type object that represents the specified type.

重载

GetType() GetType() GetType() GetType()

获取当前 TypeGets the current Type.

GetType(String) GetType(String) GetType(String) GetType(String)

获取具有指定名称的 Type,执行区分大小写的搜索。Gets the Type with the specified name, performing a case-sensitive search.

GetType(String, Boolean) GetType(String, Boolean) GetType(String, Boolean) 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) GetType(String, Boolean, Boolean) GetType(String, Boolean, Boolean) 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>) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) 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) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean) 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) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) 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() GetType() GetType() GetType()

获取当前 TypeGets the current Type.

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

返回

当前的 TypeThe current Type.

实现

异常

调用了类初始值设定项,且该项引发了异常。A class initializer is invoked and throws an exception.

另请参阅

GetType(String) GetType(String) GetType(String) GetType(String)

获取具有指定名称的 Type,执行区分大小写的搜索。Gets the Type with the specified name, performing a case-sensitive search.

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

参数

typeName
String String String String

要获取的类型的程序集限定名称。The assembly-qualified name of the type to get. 请参阅 AssemblyQualifiedNameSee AssemblyQualifiedName. 如果该类型位于当前正在执行的程序集中或者 Mscorlib.dll 中,则提供由命名空间限定的类型名称就足够了。If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

返回

具有指定名称的类型(如果找到的话);否则为 nullThe type with the specified name, if found; otherwise, 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限定名称 (可TypeAssemblyQualifiedName获取), 则可以使用方法获取其他程序集中的类型的对象。You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType导致加载中typeName指定的程序集。GetType causes loading of the assembly specified in typeName. Assembly.Load您还可以使用方法加载程序集, 然后Assembly.GetType使用或Assembly.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中C#的GetType或运算符更有效率 Visual Basic。If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

备注

如果typeName找不GetType(String)到, 则对方法的调用将null返回。If typeName cannot be found, the call to the GetType(String) method returns null. 它不会引发异常。It does not throw an exception. 若要控制是否引发异常, 请调用GetType throwOnError具有参数的方法的重载。To control whether an exception is thrown, call an overload of the GetType method that has a throwOnError parameter.

GetType仅适用于从磁盘加载的程序集。GetType only works on assemblies loaded from disk. 如果调用GetType查找System.Reflection.Emit使用服务定义的动态程序集中定义的类型, 可能会出现不一致的行为。If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. 此行为取决于动态程序集是否为持久性的, 即使用RunAndSave System.Reflection.Emit.AssemblyBuilderAccess枚举的或Save访问模式创建的。The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. 如果动态程序集是持久性的, 并且在调用之前GetType已写入磁盘, 则加载程序将在磁盘上找到保存的程序集, 加载该程序集, 并从该程序集检索该类型。If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. 如果在调用时GetType未将程序集保存到磁盘, 则该方法将返回。 nullIf the assembly has not been saved to disk when GetType is called, the method returns null. GetType不了解瞬态动态程序集;因此, 调用GetType以检索暂时性动态程序集中的类型会返回nullGetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

若要GetType在动态模块上使用, 请订阅AppDomain.AssemblyResolve事件并在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.

下表显示了在类型上反射时Get方法返回的基类成员。The 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 NoNo NoNo
字段Field NoNo 可以。Yes. 字段始终按名称和签名隐藏。A field is always hide-by-name-and-signature.
事件Event 不适用Not applicable 通用类型系统规则是指继承与实现属性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反射将属性视为隐藏的名称和签名。Reflection treats properties as hide-by-name-and-signature. 请参阅下面的注释2。See note 2 below.
方法Method NoNo 可以。Yes. 方法 (虚拟和非虚拟) 可按名称隐藏或按名称和签名隐藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
嵌套类型Nested Type NoNo NoNo
PropertyProperty 不适用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 访问器, 则派生类属性将隐藏基类属性, 并且你将无法访问基类的资源库。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。If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and Mscorlib.dll, in that order. 如果 typeName 完全限定了部分或完整的程序集名称, 则此方法将在指定的程序集中搜索。If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. 如果程序集具有强名称, 则需要完整的程序集名称。If the assembly has a strong name, a complete assembly name is required.

AssemblyQualifiedName属性返回完全限定的类型名称, 包括嵌套类型、程序集名称和泛型类型参数。The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and generic type arguments. 所有支持公共语言运行时的编译器都将发出嵌套类的简单名称, 并且在查询时, 反射将按照以下约定构造错位的名称。All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

备注

在 .NET Framework 版本2.0 中, 处理器体系结构添加到程序集标识, 并可指定为程序集名称字符串的一部分。In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. 例如, "ProcessorArchitecture = msil"。For example, "ProcessorArchitecture=msil". 不过, 由于兼容性原因, 它不包含在由AssemblyQualifiedName属性返回的字符串中。However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. 还可以通过创建AssemblyName对象并将其传递给Load方法的适当重载来加载类型。You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. 然后, 可以使用Assembly.GetType方法从程序集加载类型。You can then use the Assembly.GetType method to load types from the assembly. 另请参阅 AssemblyName.ProcessorArchitectureSee also AssemblyName.ProcessorArchitecture.

后面Delimiter 含义Meaning
反斜杠 (\)Backslash (\) 转义符。Escape 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 (.)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 + 命名空间, 则该字符串必须在加号 (+) 前面加上转义符\(), 以防止它被解释为嵌套分隔符。If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. 反射发出此字符串, 如下所示:Reflection emits this string as follows:

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

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

此限定名称可以保留, 以后用于加载TypeThis qualified name can be persisted and later used to load the Type. 若要搜索并加载Type, 请将与类型名称一起使用, 或者使用GetType带有程序集限定类型名称的。To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. GetType只有类型名称才会Type在调用方的程序集中查找, 然后在系统程序集中查找。GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. GetType具有程序集限定类型名称的将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反射从泛型方法Tuple<T> and ``\<T0, T1> 2 Tuple(Of T)和中Tuple(Of T0, T1)的 Visual Basic 或和元组 (在视觉对象C#中) 返回错位的名称元组。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>的为的可表示为,如下所示String: MyTypeA 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 的, 其中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. 例如, 字符串 "system.string Int32 " 1 [system.exception] 表示可以为 null。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++的、和GetType(Nullable(Of Boolean)) Visual Basic。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
可以为 nullInt32A 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**")
托管指针或对的引用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[*]")
一维数组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) GetType(String, Boolean) GetType(String, Boolean) GetType(String, Boolean)

获取具有指定名称的 Type,指定是否执行区分大小写的搜索,以及在找不到类型时是否引发异常。Gets the Type with the specified name, performing a case-sensitive search and specifying whether to throw an exception if the type is not found.

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

参数

typeName
String String String String

要获取的类型的程序集限定名称。The assembly-qualified name of the type to get. 请参阅 AssemblyQualifiedNameSee AssemblyQualifiedName. 如果该类型位于当前正在执行的程序集中或者 Mscorlib.dll 中,则提供由命名空间限定的类型名称就足够了。If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

throwOnError
Boolean Boolean Boolean 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.

返回

具有指定名称的类型。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.

异常

调用了类初始值设定项,且该项引发了异常。A class initializer is invoked and throws an exception.

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

-or- throwOnError 的值为 true,且 typeName 包含无效字符,例如嵌入的制表符。throwOnError is true and typeName contains invalid characters, such as an embedded tab. -or- throwOnError 的值为 true,且 typeName 为空字符串。throwOnError is true and typeName is an empty string.

- 或 --or- throwOnError 的值为 true,且 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限定名称 (可TypeAssemblyQualifiedName获取), 则可以使用方法获取其他程序集中的类型的对象。You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType导致加载中typeName指定的程序集。GetType causes loading of the assembly specified in typeName. Assembly.Load您还可以使用方法加载程序集, 然后Assembly.GetType使用或Assembly.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中C#的GetType或运算符更有效率 Visual Basic。If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

GetType仅适用于从磁盘加载的程序集。GetType only works on assemblies loaded from disk. 如果调用GetType查找System.Reflection.Emit使用服务定义的动态程序集中定义的类型, 可能会出现不一致的行为。If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. 此行为取决于动态程序集是否为持久性的, 即使用RunAndSave System.Reflection.Emit.AssemblyBuilderAccess枚举的或Save访问模式创建的。The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. 如果动态程序集是持久性的, 并且在调用之前GetType已写入磁盘, 则加载程序将在磁盘上找到保存的程序集, 加载该程序集, 并从该程序集检索该类型。If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. 如果在调用时GetType未将程序集保存到磁盘, 则该方法将返回。 nullIf the assembly has not been saved to disk when GetType is called, the method returns null. GetType不了解瞬态动态程序集;因此, 调用GetType以检索暂时性动态程序集中的类型会返回nullGetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

若要GetType在动态模块上使用, 请订阅AppDomain.AssemblyResolve事件并在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即使为false, 也会引发。For example, if the type is found but cannot be loaded, a TypeLoadException is thrown even if throwOnError is false.

下表显示了在类型上反射时Get方法返回的基类成员。The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

成员类型Member Type StaticStatic 非静态Non-Static
构造函数Constructor NoNo NoNo
字段Field NoNo 可以。Yes. 字段始终按名称和签名隐藏。A field is always hide-by-name-and-signature.
事件Event 不适用Not applicable 通用类型系统规则是指继承与实现属性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反射将属性视为隐藏的名称和签名。Reflection treats properties as hide-by-name-and-signature. 请参阅下面的注释2。See note 2 below.
方法Method NoNo 可以。Yes. 方法 (虚拟和非虚拟) 可按名称隐藏或按名称和签名隐藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
嵌套类型Nested Type NoNo NoNo
PropertyProperty 不适用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 访问器, 则派生类属性将隐藏基类属性, 并且你将无法访问基类的资源库。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。If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and Mscorlib.dll, in that order. 如果 typeName 完全限定了部分或完整的程序集名称, 则此方法将在指定的程序集中搜索。If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. 如果程序集具有强名称, 则需要完整的程序集名称。If the assembly has a strong name, a complete assembly name is required.

AssemblyQualifiedName属性返回完全限定的类型名称, 包括嵌套类型、程序集名称和泛型参数。The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and generic arguments. 所有支持公共语言运行时的编译器都将发出嵌套类的简单名称, 并且在查询时, 反射将按照以下约定构造错位的名称。All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

备注

在 .NET Framework 版本2.0 中, 处理器体系结构添加到程序集标识, 并可指定为程序集名称字符串的一部分。In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. 例如, "ProcessorArchitecture = msil"。For example, "ProcessorArchitecture=msil". 不过, 由于兼容性原因, 它不包含在由AssemblyQualifiedName属性返回的字符串中。However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. 还可以通过创建AssemblyName对象并将其传递给Load方法的适当重载来加载类型。You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. 然后, 可以使用Assembly.GetType方法从程序集加载类型。You can then use the Assembly.GetType method to load types from the assembly. 另请参阅 AssemblyName.ProcessorArchitectureSee also AssemblyName.ProcessorArchitecture.

后面Delimiter 含义Meaning
反斜杠 (\)Backslash (\) 转义符。Escape 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 (.)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 + 命名空间, 则该字符串必须在加号 (+) 前面加上转义符\(), 以防止它被解释为嵌套分隔符。If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. 反射发出此字符串, 如下所示:Reflection emits this string as follows:

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

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

此限定名称可以保留, 以后用于加载TypeThis qualified name can be persisted and later used to load the Type. 若要搜索并加载Type, 请将与类型名称一起使用, 或者使用GetType带有程序集限定类型名称的。To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. GetType只有类型名称才会Type在调用方的程序集中查找, 然后在系统程序集中查找。GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. GetType具有程序集限定类型名称的将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反射从泛型方法Tuple<T> and ``\<T0, T1> 2 Tuple(Of T)和中Tuple(Of T0, T1)的 Visual Basic 或和元组 (在视觉对象C#中) 返回错位的名称元组。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>的为的可表示为,如下所示String: MyTypeA 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 中的, 其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. 例如, 字符串 "system.string Int32 " 1 [system.exception] 表示可以为 null。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++的、和GetType(Nullable(Of Boolean)) Visual Basic。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
可以为 nullInt32A 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**")
托管指针或对的引用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[*]")
一维数组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) GetType(String, Boolean, Boolean) GetType(String, Boolean, Boolean) GetType(String, Boolean, Boolean)

获取具有指定名称的 Type,指定是否执行区分大小写的搜索,以及在找不到类型时是否引发异常。Gets the Type with the specified name, specifying whether to throw an exception if the type is not found and whether to perform a case-sensitive search.

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

参数

typeName
String String String String

要获取的类型的程序集限定名称。The assembly-qualified name of the type to get. 请参阅 AssemblyQualifiedNameSee AssemblyQualifiedName. 如果该类型位于当前正在执行的程序集中或者 Mscorlib.dll 中,则提供由命名空间限定的类型名称就足够了。If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

throwOnError
Boolean Boolean Boolean 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 Boolean Boolean Boolean

true 执行的搜索不区分大小写,则为 typeName;对 false 执行的搜索区分大小写,则为 typeNametrue to perform a case-insensitive search for typeName, false to perform a case-sensitive search for typeName.

返回

具有指定名称的类型。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.

异常

调用了类初始值设定项,且该项引发了异常。A class initializer is invoked and throws an exception.

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

-or- throwOnError 的值为 true,且 typeName 包含无效字符,例如嵌入的制表符。throwOnError is true and typeName contains invalid characters, such as an embedded tab. - 或 --or- throwOnError 的值为 true,且 typeName 为空字符串。throwOnError is true and typeName is an empty string.

-or- throwOnError 的值为 true,且 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.

throwOnError 的值为 true,且未找到程序集或程序集的某个依赖项。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限定名称 (可TypeAssemblyQualifiedName获取), 则可以使用方法获取其他程序集中的类型的对象。You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType导致加载中typeName指定的程序集。GetType causes loading of the assembly specified in typeName. Assembly.Load您还可以使用方法加载程序集, 然后Assembly.GetType使用或Assembly.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中C#的GetType或运算符更有效率 Visual Basic。If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

GetType仅适用于从磁盘加载的程序集。GetType only works on assemblies loaded from disk. 如果调用GetType查找System.Reflection.Emit使用服务定义的动态程序集中定义的类型, 可能会出现不一致的行为。If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. 此行为取决于动态程序集是否为持久性的, 即使用RunAndSave System.Reflection.Emit.AssemblyBuilderAccess枚举的或Save访问模式创建的。The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. 如果动态程序集是持久性的, 并且在调用之前GetType已写入磁盘, 则加载程序将在磁盘上找到保存的程序集, 加载该程序集, 并从该程序集检索该类型。If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. 如果在调用时GetType未将程序集保存到磁盘, 则该方法将返回。 nullIf the assembly has not been saved to disk when GetType is called, the method returns null. GetType不了解瞬态动态程序集;因此, 调用GetType以检索暂时性动态程序集中的类型会返回nullGetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

若要GetType在动态模块上使用, 请订阅AppDomain.AssemblyResolve事件并在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即使为false, 也会引发。For example, if the type is found but cannot be loaded, a TypeLoadException is thrown even if throwOnError is false.

下表显示了在类型上反射时Get方法返回的基类成员。The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

成员类型Member Type StaticStatic 非静态Non-Static
构造函数Constructor NoNo NoNo
字段Field NoNo 可以。Yes. 字段始终按名称和签名隐藏。A field is always hide-by-name-and-signature.
事件Event 不适用Not applicable 通用类型系统规则是指继承与实现属性的方法相同。The common type system rule is that the inheritance is the same as that of the methods that implement the property. 反射将属性视为隐藏的名称和签名。Reflection treats properties as hide-by-name-and-signature. 请参阅下面的注释2。See note 2 below.
方法Method NoNo 可以。Yes. 方法 (虚拟和非虚拟) 可按名称隐藏或按名称和签名隐藏。A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
嵌套类型Nested Type NoNo NoNo
PropertyProperty 不适用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 访问器, 则派生类属性将隐藏基类属性, 并且你将无法访问基类的资源库。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。If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and Mscorlib.dll, in that order. 如果 typeName 完全限定了部分或完整的程序集名称, 则此方法将在指定的程序集中搜索。If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. 如果程序集具有强名称, 则需要完整的程序集名称。If the assembly has a strong name, a complete assembly name is required.

AssemblyQualifiedName属性返回完全限定的类型名称, 包括嵌套类型、程序集名称和类型参数。The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and type arguments. 所有支持公共语言运行时的编译器都将发出嵌套类的简单名称, 并且在查询时, 反射将按照以下约定构造错位的名称。All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

备注

在 .NET Framework 版本2.0 中, 处理器体系结构添加到程序集标识, 并可指定为程序集名称字符串的一部分。In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. 例如, "ProcessorArchitecture = msil"。For example, "ProcessorArchitecture=msil". 不过, 由于兼容性原因, 它不包含在由AssemblyQualifiedName属性返回的字符串中。However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. 还可以通过创建AssemblyName对象并将其传递给Load方法的适当重载来加载类型。You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. 然后, 可以使用Assembly.GetType方法从程序集加载类型。You can then use the Assembly.GetType method to load types from the assembly. 另请参阅 AssemblyName.ProcessorArchitectureSee also AssemblyName.ProcessorArchitecture.

后面Delimiter 含义Meaning
反斜杠 (\)Backslash (\) 转义符。Escape 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 (.)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 + 命名空间, 则该字符串必须在加号 (+) 前面加上转义符\(), 以防止它被解释为嵌套分隔符。If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. 反射发出此字符串, 如下所示:Reflection emits this string as follows:

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

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

此限定名称可以保留, 以后用于加载TypeThis qualified name can be persisted and later used to load the Type. 若要搜索并加载Type, 请将与类型名称一起使用, 或者使用GetType带有程序集限定类型名称的。To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. GetType只有类型名称才会Type在调用方的程序集中查找, 然后在系统程序集中查找。GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. GetType具有程序集限定类型名称的将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反射从泛型方法Tuple<T> and ``\<T0, T1> 2 Tuple(Of T)和中Tuple(Of T0, T1)的 Visual Basic 或和元组 (在视觉对象C#中) 返回错位的名称元组。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>的为的可表示为,如下所示String: MyTypeA 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 中的, 其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. 例如, 字符串 "system.string Int32 " 1 [system.exception] 表示可以为 null。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++的、和GetType(Nullable(Of Boolean)) Visual Basic。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
可以为 nullInt32A 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**")
托管指针或对的引用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[*]")
一维数组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>) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>)

获取具有指定名称的类型,(可选)提供自定义方法以解析程序集和该类型。Gets the type with the specified name, optionally providing custom methods to resolve the assembly and the type.

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

参数

typeName
String String String 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 参数,或者使用了标准类型解析,则除非该类型位于当前正在执行的程序集或 Mscorlib.dll 中(在这种情况下足以提供其命名空间所限定的类型名称),否则 typeName 必须为程序集限定的名称(请参见 AssemblyQualifiedName)。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, 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 对象形式传递给 AssemblyName 的程序集名称。The 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.

返回

具有指定名称的类型,如果未找到该类型,则返回 nullThe type with the specified name, or null if the type is not found.

异常

调用了类初始值设定项,且该项引发了异常。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.

注解

此方法的使用方案以及有关assemblyResolvertypeResolver参数的详细信息GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean)可在方法重载中找到。Usage scenarios for this method and details about the assemblyResolver and typeResolver parameters can be found in the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload.

备注

如果typeName找不GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>)到, 则对方法的调用将null返回。If 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 throwOnError具有参数的方法的重载。To control whether an exception is thrown, call an overload of the GetType method that has a throwOnError parameter.

调用此方法重载GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean)与调用方法重载和为throwOnErrorignoreCase参数指定false的方法相同。Calling this method overload is the same as calling the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload and specifying false for the throwOnError and ignoreCase parameters.

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

获取具有指定名称的类型,指定在找不到该类型时是否引发异常,(可选)提供自定义方法以解析程序集和该类型。Gets the type with the specified name, specifying whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

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

参数

typeName
String String String 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 参数,或者使用了标准类型解析,则除非该类型位于当前正在执行的程序集或 Mscorlib.dll 中(在这种情况下足以提供其命名空间所限定的类型名称),否则 typeName 必须为程序集限定的名称(请参见 AssemblyQualifiedName)。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, 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 对象形式传递给 AssemblyName 的程序集名称。The 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 Boolean Boolean 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.

返回

具有指定名称的类型。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.

异常

调用了类初始值设定项,且该项引发了异常。A class initializer is invoked and throws an exception.

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

- 或 --or- throwOnError 的值为 true,且 typeName 包含无效字符,例如嵌入的制表符。throwOnError is true and typeName contains invalid characters, such as an embedded tab. -or- throwOnError 的值为 true,且 typeName 为空字符串。throwOnError is true and typeName is an empty string.

-or- throwOnError 的值为 true,且 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.

throwOnError 的值为 true,且未找到程序集或程序集的某个依赖项。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.

注解

此方法的使用方案以及有关assemblyResolvertypeResolver参数的详细信息GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean)可在方法重载中找到。Usage scenarios for this method and details about the assemblyResolver and typeResolver parameters can be found in the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload.

调用此方法重载与调用GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean)方法重载和为ignoreCase参数指定false的方法相同。Calling this method overload is the same as calling the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload and specifying false for the ignoreCase parameter.

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

获取具有指定名称的类型,指定是否执行区分大小写的搜索,在找不到类型时是否引发异常,(可选)提供自定义方法以解析程序集和该类型。Gets the type with the specified name, specifying whether to perform a case-sensitive search and whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

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

参数

typeName
String String String 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 参数,或者使用了标准类型解析,则除非该类型位于当前正在执行的程序集或 Mscorlib.dll 中(在这种情况下足以提供其命名空间所限定的类型名称),否则 typeName 必须为程序集限定的名称(请参见 AssemblyQualifiedName)。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, 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 对象形式传递给 AssemblyName 的程序集名称。The 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 Boolean Boolean 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 Boolean Boolean Boolean

true 执行的搜索不区分大小写,则为 typeName;对 false 执行的搜索区分大小写,则为 typeNametrue to perform a case-insensitive search for typeName, false to perform a case-sensitive search for typeName.

返回

具有指定名称的类型。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.

异常

调用了类初始值设定项,且该项引发了异常。A class initializer is invoked and throws an exception.

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

- 或 --or- throwOnError 的值为 true,且 typeName 包含无效字符,例如嵌入的制表符。throwOnError is true and typeName contains invalid characters, such as an embedded tab. -or- throwOnError 的值为 true,且 typeName 为空字符串。throwOnError is true and typeName is an empty string.

- 或 --or- throwOnError 的值为 true,且 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.

throwOnError 的值为 true,且未找到程序集或程序集的某个依赖项。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由公共语言运行时 (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 或当前正在执行的程序集的上下文中解析不合格的类型名称, 也可以选择在typeResolver参数中提供程序集。Unqualified type names can be resolved in the context of Mscorlib.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:

  • 如果方法来自未知或assemblyResolvertypeResolver受信任的调用方, 请不要将方法传递给或。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和/或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.

  • 如果throwOnErrortypeResolver FileNotFoundException assemblyResolver , 则此方法null在返回时引发, 而在返回null时引发。 TypeLoadException trueIf throwOnError is true, this method throws a TypeLoadException when typeResolver returns null, and a FileNotFoundException when assemblyResolver returns null.

  • 此方法不会捕获和assemblyResolver typeResolver引发的异常。This method does not catch exceptions thrown by assemblyResolver and typeResolver. 你负责解析程序方法引发的任何异常。You are responsible for any exceptions that are thrown by the resolver methods.

解析程序集Resolving Assemblies

方法接收一个AssemblyName对象, 该对象是通过分析中typeName包含的字符串程序集名称生成的。 assemblyResolverThe assemblyResolver method receives an AssemblyName object, which is produced by parsing the string assembly name that is included in typeName. 如果typeName不包含程序集名称, assemblyResolver则不会typeResolver调用并null将传递给。If 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无法解析程序null集, 则该方法应返回。The assemblyResolver method should return null if the assembly cannot be resolved. 如果assemblyResolver返回throwOnError true, 则不FileNotFoundException会调用, 也不会进行进一步的处理; 此外, 如果为, 则引发。 null typeResolverIf assemblyResolver returns null, typeResolver is not called and no further processing occurs; additionally, if throwOnError is true, a FileNotFoundException is thrown.

如果传递到assemblyResolver的是部分名称, 则其一个或null多个部分为。 AssemblyNameIf 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. 如果属性、属性和GetPublicKeyToken方法全部返回null, 则仅提供程序集的简单名称。 CultureInfo VersionIf 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或标准程序集探测null返回typeResolver , 则不会调用。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. 如果方法无法解析类型, 则应返回nulltypeResolverThe typeResolver method should return null if it cannot resolve the type. 如果typeResolver返回true TypeLoadException且为, 则的GetType此重载将引发。 throwOnError nullIf 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是嵌套类型, 则仅将包含类型的最外面的名称typeResolver传递给。If typeName is a nested type, only the name of the outermost containing type is passed to typeResolver. typeResolver返回此类型时GetNestedType , 将以递归方式调用方法, 直到解析最内层的嵌套类型。When typeResolver returns this type, the GetNestedType method is called recursively until the innermost nested type has been resolved.

解析泛型类型Resolving Generic Types

GetType递归调用以解析泛型类型:首先解析泛型类型本身, 然后解析其类型参数。The GetType is called recursively to resolve generic types: First to resolve the generic type itself, and then to resolve its type arguments. 如果类型参数是泛型, GetType则会以递归方式调用以解析其类型参数, 依此类推。If a type argument is generic, GetType is called recursively to resolve its type arguments, and so on.

您提供的assemblyResolvertypeResolver的组合必须能够解析此递归的所有级别。The combination of assemblyResolver and typeResolver that you provide must be capable of resolving all levels of this recursion. 例如, 假设您提供了一个assemblyResolver , 用于控制的MyAssembly加载。For example, suppose you supply an assemblyResolver that controls the loading of MyAssembly. 假设要解析泛型类型Dictionary<string, MyType> (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. null Dictionary<TKey,TValue> String必须能够处理程序集或null, 因为它将接收和。 typeResolverYour typeResolver must be able handle either an assembly or null, because it will receive null for Dictionary<TKey,TValue> and String. 它可以通过调用采用字符串的GetType方法重载来处理这种情况, 因为两个非限定类型名称都在 mscorlib.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:

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

不会为字典类型和字符串类型调用方法,因为这些类型名称不是程序集限定名称。assemblyResolverThe assemblyResolver method is not called for the dictionary type and the string type, because those type names are not assembly-qualified.

现在, 假设第一个System.String泛型参数类型为, YourAssembly而不YourType是:Now 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, 也不是当前正在执行的YourType程序集, 因此无法在没有程序集限定名称的情况下解析。Because this assembly is neither Mscorlib.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使用提供AssemblyName的对象MyAssembly执行程序集加载, 而不是为之外的程序集进行返回。Instead of returning null for assemblies other than MyAssembly, it now performs an assembly load using the supplied AssemblyName object.

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

返回到使用说明Back to Usage Notes.

解析包含特殊字符的类型名称Resolving Type Names with Special Characters

某些字符在程序集限定名称中具有特殊含义。Certain characters have special meanings in assembly-qualified names. 如果简单的类型名称包含这些字符, 则当简单名称是程序集限定名称的一部分时, 这些字符将导致分析错误。If a simple type name contains these characters, the characters cause parsing errors when the simple name is part of an assembly-qualified name. 若要避免分析错误, 必须使用反斜杠对特殊字符进行转义, 然后才能将程序集限定名称传递给GetType方法。To avoid the parsing errors, you must escape the special characters with a backslash before you can pass the assembly-qualified name to the GetType method. 例如, 如果类型Strange]Type为, 则必须将转义符添加到方括号的前面, 如下所示:。 Strange\]TypeFor example, if a type is named Strange]Type, the escape character must be added ahead of the square bracket as follows: Strange\]Type.

备注

不能在 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 character.

诸如返回正确AssemblyQualifiedName转义的字符串之类的属性。Properties such as AssemblyQualifiedName return correctly escaped strings. 必须将正确转义的GetType字符串传递给方法。You must pass correctly escaped strings to the GetType method. 相反, 该GetType方法将正确的转义名称传递typeResolver给和的默认类型解析方法。In turn, the GetType method passes correctly escaped names to typeResolver and to the default type resolution methods. 如果需要将名称与中typeResolver的非转义名称进行比较, 则必须删除转义符。If you need to compare a name to an unescaped name in typeResolver, you must remove the escape characters.

返回到使用说明Back to Usage Notes.

混合名称解析Mixed Name Resolution

下表总结了、 assemblyResolver typeResolver和默认名称解析之间的交互, 适用于中typeName的类型名称和程序集名称的所有组合:The following table summarizes the interactions between assemblyResolver, typeResolver, and default name resolution, for all combinations of type name and assembly name in typeName:

类型名称的内容Contents of type name 程序集解析程序方法Assembly resolver method 类型解析程序方法Type resolver method 结果Result
类型、程序集type, assembly nullnull nullnull 等效于调用Type.GetType(String, Boolean, Boolean)方法重载。Equivalent to calling the Type.GetType(String, Boolean, Boolean) method overload.
类型、程序集type, assembly 规定provided nullnull assemblyResolver返回程序集, 如果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, assembly nullnull 规定provided 等效于将程序集名称转换为AssemblyName对象, 并Assembly.Load(AssemblyName)调用方法重载以获取程序集。Equivalent to converting the assembly name to an AssemblyName object and calling the Assembly.Load(AssemblyName) method overload to get the assembly. 如果对程序集进行解析, 则将其typeResolver传递到; typeResolver否则, 将不会调用, 也不会再尝试解析该类型。If the assembly is resolved, it is passed to typeResolver; otherwise, typeResolver is not called and there is no further attempt to resolve the type.
类型、程序集type, assembly 规定provided 规定provided assemblyResolver返回程序集, 如果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, provided nullnull 等效于调用Type.GetType(String, Boolean, Boolean)方法重载。Equivalent to calling the Type.GetType(String, Boolean, Boolean) method overload. 由于未提供程序集名称, 因此只会搜索 Mscorlib.dll 和当前正在执行的程序集。Because the assembly name is not provided, only Mscorlib.dll and the currently executing assembly are searched. 如果assemblyResolver提供了, 则将其忽略。If assemblyResolver is provided, it is ignored.
类型type 提供空值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 提供空值null, provided 提供空值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.

适用于