Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Übersetzung
Englisch

Type.GetType-Methode: (String, Boolean)

 

Veröffentlicht: Juli 2016

Ruft den Type mit dem angegebenen Namen ab. Bei der Suche wird die Groß-/Kleinschreibung beachtet. Dabei wird angegeben, ob eine Ausnahme ausgelöst werden soll, wenn der Typ nicht gefunden wird.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

public static Type GetType(
	string typeName,
	bool throwOnError
)

Parameter

typeName
Type: System.String

Der durch die Assembly bezeichnete Name des abzurufenden Typs. Siehe AssemblyQualifiedName. Wenn sich der Typ in der aktuell ausgeführten Assembly oder in Mscorlib.dll befindet, ist eine Angabe des Typnamens einschließlich des qualifizierenden Namespace ausreichend.

throwOnError
Type: System.Boolean

true, damit eine Ausnahme ausgelöst wird, wenn der Typ nicht gefunden werden kann, false, damit null zurückgegeben wird. Die Angabe von false unterdrückt auch einige andere Ausnahmebedingungen, aber nicht alle. Informationen finden Sie im Abschnitt für Ausnahmen.

Rückgabewert

Type: System.Type

Der Typ mit dem angegebenen Namen. Wenn der Typ nicht gefunden wird, gibt der throwOnError-Parameter an, ob null zurückgegeben oder eine Ausnahme ausgelöst wird. In einigen Fällen wird unabhängig vom Wert von throwOnError eine Ausnahme ausgelöst. Informationen finden Sie im Abschnitt für Ausnahmen.

Exception Condition
ArgumentNullException

typeName ist null.

TargetInvocationException

Ein Klasseninitialisierer wird aufgerufen und löst eine Ausnahme aus.

TypeLoadException

throwOnError ist true, und der Typ wurde nicht gefunden.

- oder -

throwOnError ist true, und typeName enthält ungültige Zeichen, z. B. ein eingebettetes Tabstoppzeichen.

- oder -

throwOnError ist true, und typeName ist eine leere Zeichenfolge.

- oder -

throwOnError ist true, und typeName stellt einen Arraytyp mit einer ungültigen Größe dar.

- oder -

typeName stellt ein Array von TypedReference dar.

ArgumentException

throwOnError ist true, und typeName enthält ungültige Syntax, beispielsweise "MyType[,*,]".

- oder -

typeName stellt einen generischen Typ dar, der einen Zeigertyp, einen ByRef-Typ oder Void als eines seiner Typargumente aufweist.

- oder -

typeName stellt einen generischen Typ dar, der eine falsche Anzahl von Typargumenten aufweist.

- oder -

typeName stellt einen generischen Typ dar, und eines seiner Typargumente erfüllt nicht die Einschränkungen für den entsprechenden Typparameter.

FileNotFoundException

throwOnError ist true, und die Assembly oder eine der zugehörigen Abhängigkeiten wurde nicht gefunden.

FileLoadException
System_CAPS_noteHinweis

Fangen Sie in .NET für Windows Store-Apps oder der portablen Klassenbibliothek stattdessen die Basisklassenausnahme IOException ab.

Die Assembly oder eine der zugehörigen Abhängigkeiten wurde gefunden, konnte aber nicht geladen werden.

BadImageFormatException

Die Assembly oder eine der zugehörigen Abhängigkeiten ist ungültig.

- oder -

Version 2.0 oder höher der Common Language Runtime ist derzeit geladen, und die Assembly wurde mit einer höheren Version kompiliert.

You can use the M:System.Type.GetType method to obtain a T:System.Type object for a type in another assembly, if the you know its namespace-qualified name. M:System.Type.GetType causes loading of the assembly specified in typeName. You can also load an assembly using the M:System.Reflection.Assembly.Load(System.Reflection.AssemblyName) method, and then use the M:System.Type.GetType or M:System.Reflection.Assembly.GetTypes methods of the T:System.Reflection.Assembly class to get T:System.Type objects. If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C#, M:System.Type.GetType in Visual Basic, or typeid in C++.

GetType only works on assemblies loaded from disk. 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. 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. 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. If the assembly has not been saved to disk when GetType is called, the method returns null. GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

To use GetType on a dynamic module, subscribe to the E:System.AppDomain.AssemblyResolve event and call GetType before saving. Otherwise, you will get two copies of the assembly in memory.

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. Some exceptions are thrown regardless of the value of throwOnError. For example, if the type is found but cannot be loaded, a T:System.TypeLoadException is thrown even if throwOnError is false.

The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

Member Type

Static

Non-Static

Constructor

No

No

Field

No

Yes. A field is always hide-by-name-and-signature.

Event

Not applicable

The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.

Method

No

Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.

Nested Type

No

No

Property

Not applicable

The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.

  1. 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. 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.

Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.

typeName can be the type name qualified by its namespace or an assembly-qualified name that includes an assembly name specification. See AssemblyQualifiedName.

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

The P:System.Type.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.

System_CAPS_noteHinweis

In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. For example, "ProcessorArchitecture=msil". However, it is not included in the string returned by the P:System.Type.AssemblyQualifiedName property, for compatibility reasons. You can also load types by creating an T:System.Reflection.AssemblyName object and passing it to an appropriate overload of the Overload:System.Reflection.Assembly.Load method. You can then use the M:System.Reflection.Assembly.GetType(System.String) method to load types from the assembly. See also P:System.Reflection.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 (.)

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

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 "\\".

This qualified name can be persisted and later used to load the T:System.Type. To search for and load a T:System.Type, use M:System.Type.GetType either with the type name only or with the assembly qualified type name. M:System.Type.GetType with the type name only will look for the T:System.Type in the caller's assembly and then in the System assembly. M:System.Type.GetType with the assembly qualified type name will look for the T:System.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. 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. For example, reflection returns the mangled names Tuple`1 and Tuple`2 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. For example, a generic T:System.Collections.Generic.Dictionary`2 has two type parameters. A T:System.Collections.Generic.Dictionary`2 of MyType with keys of type T:System.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. For example, a T:System.Collections.Generic.Dictionary`2 of MyType from MyAssembly.dll, with keys of type T:System.String, might be specified as follows:

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

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.

Nullable types are a special case of generic types. For example, a nullable T:System.Int32 is represented by the string "System.Nullable`1[System.Int32]".

System_CAPS_noteHinweis

In C#, C++, and Visual Basic you can also get nullable types using type operators. For example, the nullable T:System.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.

The following table shows the syntax you use with GetType for various types.

To Get

Use

A nullable T:System.Int32

Type.GetType("System.Nullable`1[System.Int32]")

An unmanaged pointer to MyType

Type.GetType("MyType*")

An unmanaged pointer to a pointer to MyType

Type.GetType("MyType**")

A managed pointer or reference to 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")

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

A comma (,) inside the brackets a total of n-1 times. 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]]")

The following example retrieves the type of System.Int32 and uses that type object to display the P:System.Type.FullName property of System.Int32. If a type object refers to an assembly that does not exist, this example throws an exception.

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

Universelle Windows-Plattform
Verfügbar seit 8
.NET Framework
Verfügbar seit 1.1
Portierbare Klassenbibliothek
Unterstützt in: portierbare .NET-Plattformen
Silverlight
Verfügbar seit 2.0
Windows Phone Silverlight
Verfügbar seit 7.0
Windows Phone
Verfügbar seit 8.1
Zurück zum Anfang
Anzeigen: