Object.GetType Methode

Definition

Ruft den Type der aktuellen Instanz ab.Gets the Type of the current instance.

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

Gibt zurück

Der genaue Laufzeittyp der aktuellen Instanz.The exact runtime type of the current instance.

Beispiele

Hinweis

Einige der C#-Beispiele in diesem Artikel werden in der Inlinecodeausführung und dem Playground von Try.NET ausgeführt.Some of the C# examples in this article run in the Try.NET inline code runner and playground. Wenn vorhanden, klicken Sie auf die Schaltfläche Ausführen, um ein Beispiel in einem interaktiven Fenster auszuführen.When present, select the Run button to run an example in an interactive window. Nachdem Sie den Code ausgeführt haben, können Sie ihn ändern und den geänderten Code durch erneutes Anklicken der Schaltfläche Ausführen ausführen.Once you execute the code, you can modify it and run the modified code by selecting Run again. Der geänderte Code wird entweder im interaktiven Fenster ausgeführt, oder das interaktive Fenster zeigt alle C#-Compilerfehlermeldungen an, wenn die Kompilierung fehlschlägt.The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

Im folgenden Codebeispiel wird veranschaulicht, dass GetType den Lauf Zeittyp der aktuellen Instanz zurückgibt.The following code example demonstrates that GetType returns the runtime type of the current instance.

using namespace System;

public ref class MyBaseClass {};

public ref class MyDerivedClass: MyBaseClass{};

int main()
{
   MyBaseClass^ myBase = gcnew MyBaseClass;
   MyDerivedClass^ myDerived = gcnew MyDerivedClass;
   Object^ o = myDerived;
   MyBaseClass^ b = myDerived;
   Console::WriteLine( "mybase: Type is {0}", myBase->GetType() );
   Console::WriteLine( "myDerived: Type is {0}", myDerived->GetType() );
   Console::WriteLine( "object o = myDerived: Type is {0}", o->GetType() );
   Console::WriteLine( "MyBaseClass b = myDerived: Type is {0}", b->GetType() );
}

/*

This code produces the following output.

mybase: Type is MyBaseClass
myDerived: Type is MyDerivedClass
object o = myDerived: Type is MyDerivedClass
MyBaseClass b = myDerived: Type is MyDerivedClass 

*/
using System;

public class MyBaseClass {
}

public class MyDerivedClass: MyBaseClass {
}

public class Test 
{
   public static void Main() 
   {
      MyBaseClass myBase = new MyBaseClass();
      MyDerivedClass myDerived = new MyDerivedClass();
      object o = myDerived;
      MyBaseClass b = myDerived;

      Console.WriteLine("mybase: Type is {0}", myBase.GetType());
      Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
      Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
      Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
   }
}
// The example displays the following output:
//    mybase: Type is MyBaseClass
//    myDerived: Type is MyDerivedClass
//    object o = myDerived: Type is MyDerivedClass
//    MyBaseClass b = myDerived: Type is MyDerivedClass 
' Define a base and a derived class.
Public Class MyBaseClass
End Class 

Public Class MyDerivedClass : Inherits MyBaseClass
End Class 

Public Class Test
    Public Shared Sub Main() 
        Dim base As New MyBaseClass()
        Dim derived As New MyDerivedClass()
        Dim o As Object = derived
        Dim b As MyBaseClass = derived
        
        Console.WriteLine("base.GetType returns {0}", base.GetType())
        Console.WriteLine("derived.GetType returns {0}", derived.GetType())
        Console.WriteLine("Dim o As Object = derived; o.GetType returns {0}", o.GetType())
        Console.WriteLine("Dim b As MyBaseClass = derived; b.Type returns {0}", b.GetType())
    End Sub 
End Class 
' The example displays the following output:
'    base.GetType returns MyBaseClass
'    derived.GetType returns MyDerivedClass
'    Dim o As Object = derived; o.GetType returns MyDerivedClass
'    Dim b As MyBaseClass = derived; b.Type returns MyDerivedClass

Hinweise

Da System.Object die Basisklasse für alle Typen im .net-Typsystem ist, kann die GetType-Methode verwendet werden, um Type-Objekte zurückzugeben, die alle .NET-Typen darstellen.Because System.Object is the base class for all types in the .NET type system, the GetType method can be used to return Type objects that represent all .NET types. .Net erkennt die folgenden fünf Kategorien von Typen:.NET recognizes the following five categories of types:

Bei zwei Objekten x und y, die identische Lauf Zeit Typen aufweisen, gibt Object.ReferenceEquals(x.GetType(),y.GetType()) truezurück.For two objects x and y that have identical runtime types, Object.ReferenceEquals(x.GetType(),y.GetType()) returns true. Im folgenden Beispiel wird die GetType-Methode mit der ReferenceEquals-Methode verwendet, um zu bestimmen, ob ein numerischer Wert dem gleichen Typ wie zwei andere numerische Werte entspricht.The following example uses the GetType method with the ReferenceEquals method to determine whether one numeric value is the same type as two other numeric values.

int n1 = 12;
int n2 = 82;
long n3 = 12;

Console.WriteLine("n1 and n2 are the same type: {0}",
                  Object.ReferenceEquals(n1.GetType(), n2.GetType()));
Console.WriteLine("n1 and n3 are the same type: {0}",
                  Object.ReferenceEquals(n1.GetType(), n3.GetType()));

// The example displays the following output:
//       n1 and n2 are the same type: True
//       n1 and n3 are the same type: False      
Module Example
   Public Sub Main()
      Dim n1 As Integer = 12
      Dim n2 As Integer = 82
      Dim n3 As Long = 12
      
      Console.WriteLine("n1 and n2 are the same type: {0}",
                        Object.ReferenceEquals(n1.GetType(), n2.GetType()))
      Console.WriteLine("n1 and n3 are the same type: {0}",
                        Object.ReferenceEquals(n1.GetType(), n3.GetType()))
   End Sub
End Module
' The example displays the following output:
'       n1 and n2 are the same type: True
'       n1 and n3 are the same type: False      

Hinweis

Um zu ermitteln, ob ein Objekt ein bestimmter Typ ist, können Sie das typvergleichs Schlüsselwort oder das Konstrukt ihrer Sprache verwenden.To determine whether an object is a specific type, you can use your language's type comparison keyword or construct. Beispielsweise können Sie das TypeOf…Is-Konstrukt in Visual Basic oder das is-Schlüsselwort C#in verwenden.For example, you can use the TypeOf…Is construct in Visual Basic or the is keyword in C#.

Die GetType-Methode wird von allen Typen geerbt, die von Objectabgeleitet werden.The GetType method is inherited by all types that derive from Object. Dies bedeutet, dass Sie zusätzlich zur Verwendung des Vergleichs Schlüsselworts ihrer eigenen Sprache die GetType-Methode verwenden können, um den Typ eines bestimmten Objekts zu bestimmen, wie im folgenden Beispiel gezeigt.This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.

object[] values = { (int) 12, (long) 10653, (byte) 12, (sbyte) -5,
                   16.3, "string" }; 
foreach (var value in values) {
   Type t = value.GetType();
   if (t.Equals(typeof(byte)))
      Console.WriteLine("{0} is an unsigned byte.", value);
   else if (t.Equals(typeof(sbyte)))
      Console.WriteLine("{0} is a signed byte.", value);
   else if (t.Equals(typeof(int)))   
      Console.WriteLine("{0} is a 32-bit integer.", value);
   else if (t.Equals(typeof(long)))   
      Console.WriteLine("{0} is a 32-bit integer.", value);
   else if (t.Equals(typeof(double)))
      Console.WriteLine("{0} is a double-precision floating point.", 
                        value);
   else
      Console.WriteLine("'{0}' is another data type.", value);
}

// The example displays the following output:
//    12 is a 32-bit integer.
//    10653 is a 32-bit integer.
//    12 is an unsigned byte.
//    -5 is a signed byte.
//    16.3 is a double-precision floating point.
//    'string' is another data type.
Module Example
   Public Sub Main()
      Dim values() As Object = { 12, CLng(10653), CByte(12), 
                                 CSbyte(-5), 16.3, "string" } 
      For Each value In values
         Dim t AS Type = value.GetType()
         If t.Equals(GetType(Byte))
            Console.WriteLine("{0} is an unsigned byte.", value)
         ElseIf t.Equals(GetType(SByte))
            Console.WriteLine("{0} is a signed byte.", value)
         ElseIf t.Equals(GetType(Integer))   
            Console.WriteLine("{0} is a 32-bit integer.", value)
         ElseIf t.Equals(GetType(Long))   
            Console.WriteLine("{0} is a 32-bit integer.", value)
         ElseIf t.Equals(GetType(Double))
            Console.WriteLine("{0} is a double-precision floating point.", 
                              value)
         Else
            Console.WriteLine("'{0}' is another data type.", value)
         End If   
      Next      
   End Sub
End Module
' The example displays the following output:
'       12 is a 32-bit integer.
'       10653 is a 32-bit integer.
'       12 is an unsigned byte.
'       -5 is a signed byte.
'       16.3 is a double-precision floating point.
'       'string' is another data type.

Das Type-Objekt macht die Metadaten verfügbar, die der-Klasse der aktuellen Objectzugeordnet sind.The Type object exposes the metadata associated with the class of the current Object.

Gilt für:

Siehe auch