Type.IsAssignableFrom(Type) Type.IsAssignableFrom(Type) Type.IsAssignableFrom(Type) Type.IsAssignableFrom(Type) Method

Definition

Bestimmt, ob eine Instanz des angegebenen Typs einer Variablen des aktuellen Typs zugewiesen werden kann.Determines whether an instance of a specified type can be assigned to a variable of the current type.

public:
 virtual bool IsAssignableFrom(Type ^ c);
public virtual bool IsAssignableFrom (Type c);
abstract member IsAssignableFrom : Type -> bool
override this.IsAssignableFrom : Type -> bool
Public Overridable Function IsAssignableFrom (c As Type) As Boolean

Parameter

c
Type Type Type Type

Der Typ, der mit dem aktuellen Typ verglichen werden soll.The type to compare with the current type.

Gibt zurück

true, wenn eine der folgenden Bedingungen erfüllt ist:true if any of the following conditions is true:

  • c und die aktuelle Instanz haben denselben Typ.
  • c and the current instance represent the same type.

  • c ist entweder direkt oder indirekt von der aktuellen Instanz abgeleitet.
  • c is derived either directly or indirectly from the current instance.
  • c wird direkt von der aktuellen Instanz abgeleitet, wenn es von der aktuellen Instanz erbt; c wird indirekt von der aktuellen Instanz abgeleitet, wenn es von einer Folge von einer oder mehr Klassen erbt, die von der aktuellen Instanz erben.c is derived directly from the current instance if it inherits from the current instance; c is derived indirectly from the current instance if it inherits from a succession of one or more classes that inherit from the current instance.

    – Die aktuelle Instanz ist eine Schnittstelle, die von c implementiert wird.- The current instance is an interface that c implements.

    • c ist ein generischer Typparameter, und die aktuelle Instanz stellt eine der Einschränkungen von c dar.
  • c is a generic type parameter, and the current instance represents one of the constraints of c.
  • Im folgenden Beispiel handelt es sich bei der aktuellen Instanz um ein Type-Objekt, das die Klasse Stream darstellt.In the following example, the current instance is a Type object that represents the Stream class. Bei GenericWithConstraint handel es sich um einen generische Typ, dessen generischer Typparameter vom Typ Stream sein muss.GenericWithConstraint is a generic type whose generic type parameter must be of type Stream. Wenn der generische Typparameter an IsAssignableFrom(Type) übergeben wird,zeigt dies, dass eine Instanz des generischen Typparameters einem Stream-Objekt zugewiesen werden kann.Passing its generic type parameter to the IsAssignableFrom(Type) indicates that an instance of the generic type parameter can be assigned to an Stream object.

    [!code-csharpSystem.Type.IsAssignableFrom#2] [!code-vbSystem.Type.IsAssignableFrom#2][!code-csharpSystem.Type.IsAssignableFrom#2] [!code-vbSystem.Type.IsAssignableFrom#2]

    • c stellt einen Werttyp dar, und die aktuelle Instanz stellt Nullable<c> (Nullable(Of c) in Visual Basic) dar.
  • c represents a value type, and the current instance represents Nullable<c> (Nullable(Of c) in Visual Basic).
  • false, wenn keine dieser Bedingungen erfüllt sind oder wenn cnull ist.false if none of these conditions are true, or if c is null.

    Implementiert

    Beispiele

    Im folgenden Beispiel wird die IsAssignableFrom -Methode veranschaulicht, indem definierte Klassen, ganzzahlige Arrays und Generika verwendet werden.The following example demonstrates the IsAssignableFrom method using defined classes, integer arrays, and generics.

    using namespace System;
    using namespace System::Collections::Generic;
    
    ref class Room
    {
    };
    
    ref class Kitchen : Room
    {
    };
    
    ref class Bedroom : Room
    {
    };
    
    ref class Guestroom : Bedroom
    {
    };
    
    ref class MasterBedroom : Bedroom
    {
    };
    
    ref class Program
    {
    public:
        static void Main()
        {
                // Demonstrate classes:
                Console::WriteLine("Defined Classes:");
                Room^ room1 = gcnew Room();
                Kitchen^ kitchen1 = gcnew Kitchen();
                Bedroom^ bedroom1 = gcnew Bedroom();
                Guestroom^ guestroom1 = gcnew Guestroom();
                MasterBedroom^ masterbedroom1 = gcnew MasterBedroom();
    
                Type^ room1Type = room1->GetType();
                Type^ kitchen1Type = kitchen1->GetType();
                Type^ bedroom1Type = bedroom1->GetType();
                Type^ guestroom1Type = guestroom1->GetType();
                Type^ masterbedroom1Type = masterbedroom1->GetType();
    
                Console::WriteLine("room assignable from kitchen: {0}", room1Type->IsAssignableFrom(kitchen1Type));
                Console::WriteLine("bedroom assignable from guestroom: {0}", bedroom1Type->IsAssignableFrom(guestroom1Type));
                Console::WriteLine("kitchen assignable from masterbedroom: {0}", kitchen1Type->IsAssignableFrom(masterbedroom1Type));
    
                // Demonstrate arrays:
                Console::WriteLine();
                Console::WriteLine("Integer arrays:");
                array<Int32>^ array2 = gcnew array<Int32>(2);
                array<Int32>^ array10 = gcnew array<Int32>(10);
                array<Int32, 2>^ array22 = gcnew array<Int32, 2>(2, 2);
                array<Int32, 2>^ array24 = gcnew array<Int32, 2>(2, 4);
    
                Type^ array2Type = array2->GetType();
                Type^ array10Type = array10->GetType();
                Type^ array22Type = array22->GetType();
                Type^ array24Type = array24->GetType();
    
                Console::WriteLine("Int32[2] assignable from Int32[10]: {0}", array2Type->IsAssignableFrom(array10Type));
                Console::WriteLine("Int32[2] assignable from Int32[2,4]: {0}", array2Type->IsAssignableFrom(array24Type));
                Console::WriteLine("Int32[2,4] assignable from Int32[2,2]: {0}", array24Type->IsAssignableFrom(array22Type));
    
                // Demonstrate generics:
                Console::WriteLine();
                Console::WriteLine("Generics:");
    
                // Note that "int?[]" is the same as "Nullable<int>[]"
                //int?[] arrayNull = new int?[10];
                array<Nullable^>^ arrayNull = gcnew array<Nullable^>(10);
                List<Int32>^ genIntList = gcnew List<Int32>();
                List<Type^>^ genTList = gcnew List<Type^>();
    
                Type^ arrayNullType = arrayNull->GetType();
                Type^ genIntListType = genIntList->GetType();
                Type^ genTListType = genTList->GetType();
    
                Console::WriteLine("Int32[10] assignable from Nullable[10]: {0}", array10Type->IsAssignableFrom(arrayNullType));
                Console::WriteLine("List<Int32> assignable from List<Type^>: {0}", genIntListType->IsAssignableFrom(genTListType));
                Console::WriteLine("List<Type^> assignable from List<Int32>: {0}", genTListType->IsAssignableFrom(genIntListType));
    
                Console::ReadLine();
        }
    };
    
    int main()
    {
        Program::Main();
    }
    
    //This code example produces the following output:
    //
    // Defned Classes:
    // room assignable from kitchen: True
    // bedroom assignable from guestroom: True
    //kitchen assignable from masterbedroom: False
    //
    // Integer arrays:
    // Int32[2] assignable from Int32[10]: True
    // Int32[2] assignable from Int32[2,4]: False
    // Int32[2,4] assignable from Int32[2,2]: True
    //
    // Generics:
    // Int32[10] assignable from Nullable[10]: False
    // List<Int32> assignable from List<Type^>: False
    // List<Type^> assignable from List<Int32>: False
    
    using System;
    using System.Collections.Generic;
    class Program
    {
        public static void Main()
        {
                // Demonstrate classes:
                Console.WriteLine("Defined Classes:");
                Room room1 = new Room();
                Kitchen kitchen1 = new Kitchen();
                Bedroom bedroom1 = new Bedroom();
                Guestroom guestroom1 = new Guestroom();
                MasterBedroom masterbedroom1 = new MasterBedroom();
    
                Type room1Type = room1.GetType();
                Type kitchen1Type = kitchen1.GetType();
                Type bedroom1Type = bedroom1.GetType();
                Type guestroom1Type = guestroom1.GetType();
                Type masterbedroom1Type = masterbedroom1.GetType();
    
                Console.WriteLine("room assignable from kitchen: {0}", room1Type.IsAssignableFrom(kitchen1Type));
                Console.WriteLine("bedroom assignable from guestroom: {0}", bedroom1Type.IsAssignableFrom(guestroom1Type));
                Console.WriteLine("kitchen assignable from masterbedroom: {0}", kitchen1Type.IsAssignableFrom(masterbedroom1Type));
    
                // Demonstrate arrays:
                Console.WriteLine();
                Console.WriteLine("Integer arrays:");
    
                int[] array2 = new int[2];
                int[] array10 = new int[10];
                int[,] array22 = new int[2, 2];
                int[,] array24 = new int[2, 4];
    
                Type array2Type = array2.GetType();
                Type array10Type = array10.GetType();
                Type array22Type = array22.GetType();
                Type array24Type = array24.GetType();
    
                Console.WriteLine("int[2] assignable from int[10]: {0}", array2Type.IsAssignableFrom(array10Type));
                Console.WriteLine("int[2] assignable from int[2,4]: {0}", array2Type.IsAssignableFrom(array24Type));
                Console.WriteLine("int[2,4] assignable from int[2,2]: {0}", array24Type.IsAssignableFrom(array22Type));
    
                // Demonstrate generics:
                Console.WriteLine();
                Console.WriteLine("Generics:");
    
                // Note that "int?[]" is the same as "Nullable<int>[]"
                int?[] arrayNull = new int?[10];
                List<int> genIntList = new List<int>();
                List<Type> genTList = new List<Type>();
    
                Type arrayNullType = arrayNull.GetType();
                Type genIntListType = genIntList.GetType();
                Type genTListType = genTList.GetType();
    
                Console.WriteLine("int[10] assignable from int?[10]: {0}", array10Type.IsAssignableFrom(arrayNullType));
                Console.WriteLine("List<int> assignable from List<Type>: {0}", genIntListType.IsAssignableFrom(genTListType));
                Console.WriteLine("List<Type> assignable from List<int>: {0}", genTListType.IsAssignableFrom(genIntListType));
    
                Console.ReadLine();
    
        }
    }
    class Room
    {
    }
    
    class Kitchen : Room
    {
    }
    
    class Bedroom : Room
    {
    }
    
    class Guestroom : Bedroom
    {
    }
    
    class MasterBedroom : Bedroom
    {
    }
    
    //This code example produces the following output:
    //
    // Defned Classes:
    // room assignable from kitchen: True
    // bedroom assignable from guestroom: True
    // kitchen assignable from masterbedroom: False
    //
    // Integer arrays:
    // int[2] assignable from int[10]: True
    // int[2] assignable from int[2,4]: False
    // int[2,4] assignable from int[2,2]: True
    //
    // Generics:
    // int[10] assignable from int?[10]: False
    // List<int> assignable from List<Type>: False
    // List<Type> assignable from List<int>: False
    
    Imports System.Collections.Generic
    
    Module Example
        Public Sub Main()
            Console.WriteLine("Defined Classes:")
            Dim room1 As New Room()
            Dim kitchen1 As New Kitchen()
            Dim bedroom1 As New Bedroom()
            Dim guestroom1 As New Guestroom()
            Dim masterbedroom1 As New MasterBedroom()
    
            Dim room1Type As Type = room1.GetType()
            Dim kitchen1Type As Type = kitchen1.GetType()
            Dim bedroom1Type As Type = bedroom1.GetType()
            Dim guestroom1Type As Type = guestroom1.GetType()
            Dim masterbedroom1Type As Type = masterbedroom1.GetType()
    
            Console.WriteLine("room assignable from kitchen: {0}", room1Type.IsAssignableFrom(kitchen1Type))
            Console.WriteLine("bedroom assignable from guestroom: {0}", bedroom1Type.IsAssignableFrom(guestroom1Type))
            Console.WriteLine("kitchen assignable from masterbedroom: {0}", kitchen1Type.IsAssignableFrom(masterbedroom1Type))
    
            ' Demonstrate arrays:
            Console.WriteLine()
            Console.WriteLine("Integer arrays:")
    
            Dim array10(10) As Integer
            Dim array2(2) As Integer
            Dim array22(2, 2) As Integer
            Dim array24(2, 4) As Integer
    
            Dim array10Type As Type = array10.GetType
            Dim array2Type As Type = array2.GetType
            Dim array22Type As Type = array22.GetType
            Dim array24Type As Type = array24.GetType
    
            Console.WriteLine("Integer(2) assignable from Integer(10): {0}", array2Type.IsAssignableFrom(array10Type))
            Console.WriteLine("Integer(2) assignable from Integer(2,4): {0}", array2Type.IsAssignableFrom(array24Type))
            Console.WriteLine("Integer(2,4) assignable from Integer(2,2): {0}", array24Type.IsAssignableFrom(array22Type))
    
            ' Demonstrate generics:
            Console.WriteLine()
            Console.WriteLine("Generics:")
    
            Dim arrayNull(10) As Nullable(Of Integer)
            Dim genIntList As New List(Of Integer)
            Dim genTList As New List(Of Type)
    
            Dim arrayNullType As Type = arrayNull.GetType
            Dim genIntListType As Type = genIntList.GetType
            Dim genTListType As Type = genTList.GetType
    
            Console.WriteLine("Integer(10) assignable from Nullable(Of Integer)(10): {0}", array10Type.IsAssignableFrom(arrayNullType))
            Console.WriteLine("List(Of Integer) assignable from List(Of Type): {0}", genIntListType.IsAssignableFrom(genTListType))
            Console.WriteLine("List(Of Type) assignable from List(Of Integer): {0}", genTListType.IsAssignableFrom(genIntListType))
            Console.ReadLine()
        End Sub
    End Module
    
    Class Room
    End Class
    
    Class Kitchen : Inherits Room
    End Class
    
    Class Bedroom : Inherits Room
    End Class
    
    Class Guestroom : Inherits Bedroom
    End Class
    
    Class MasterBedroom : Inherits Bedroom
    End Class
    ' The example displays the following output:
    '    Defined Classes:
    '    room assignable from kitchen: True
    '    bedroom assignable from guestroom: True
    '    kitchen assignable from masterbedroom: False
    '
    '    Integer arrays:
    '    Integer(2) assignable from Integer(10): True
    '    Integer(2) assignable from Integer(2,4): False
    '    Integer(2,4) assignable from Integer(2,2): True
    '
    '    Generics:
    '    Integer(10) assignable from Nullable(Of Integer)(10): False
    '    List(Of Integer) assignable from List(Of Type): False
    '    List(Of Type) assignable from List(Of Integer): False
    

    Hinweise

    Die IsAssignableFrom -Methode kann verwendet werden, um zu bestimmen, c ob eine Instanz von einer Instanz des aktuellen Typs zugewiesen werden kann. die-Methode ist besonders nützlich, wenn Sie Objekte verarbeiten, deren Typen zur Entwurfszeit nicht bekannt sind, und eine bedingte Zuweisung, wie im folgenden Beispiel gezeigt.The IsAssignableFrom method can be used to determine whether an instance of c can be assigned to an instance of the current type, The method is most useful when you are handling objects whose types are not known at design time and allows for conditional assignment, as the following example shows.

    using System;
    using System.Collections;
    
    public class Example
    {
       public static void Main()
       {
          Type t = typeof(IEnumerable);
          Type c = typeof(Array);
          
          IEnumerable instanceOfT;
          int[] instanceOfC = { 1, 2, 3, 4 };
          if (t.IsAssignableFrom(c))
             instanceOfT = instanceOfC;
      }
    }
    
    Imports System.Collections
    
    Module Example
       Public Sub Main()
          Dim t As Type = GetType(IEnumerable)
          Dim c As Type = GetType(Array)
          
          Dim instanceOfT As IEnumerable
          Dim instanceOfC As Integer() = { 1, 2, 3, 4 }
          If t.IsAssignableFrom(c) Then
             instanceOfT = instanceOfC
          End If  
       End Sub
    End Module
    

    Durch diese Methode wird sichergestellt, dass eine Codezeile wie die folgende zur Laufzeit ausgeführt wird, InvalidCastException ohne eine Ausnahme auszulösen oder eine ähnliche Ausnahme auszulösen:This method thus ensures that a line of code like the following will execute at runtime without throwing an InvalidCastException exception or a similar exception:

    instanceOfT = instanceOfC;
    
    instanceOfT = instanceOfC
    

    Diese Methode kann von einer abgeleiteten Klasse überschrieben werden.This method can be overridden by a derived class.

    Hinweis

    Eine generische Typdefinition kann nicht aus einem geschlossenen konstruierten Typ zugewiesen werden.A generic type definition is not assignable from a closed constructed type. Das heißt, Sie können den geschlossenen konstruierten Typ MyGenericList<int> (MyGenericList(Of Integer) in Visual Basic) nicht einer Variablen des Typs MyGenericList<T>zuweisen.That is, you cannot assign the closed constructed type MyGenericList<int> (MyGenericList(Of Integer) in Visual Basic) to a variable of type MyGenericList<T>.

    Wenn der c -Parameter vom Typ TypeBuilderist, basiert das Ergebnis auf dem Typ, der erstellt werden soll.If the c parameter is of type TypeBuilder, the result is based on the type that is to be built. Das folgende Codebeispiel veranschaulicht dies mithilfe eines erstellten Typs mit Bdem Namen.The following code example demonstrates this using a built type named B.

    using System;
    using System.Reflection;
    using System.Reflection.Emit;
    
    public class A
    {}
    
    public class Example
    {
       public static void Main()
       {
          AppDomain domain = AppDomain.CurrentDomain;
          AssemblyName assemName = new AssemblyName();
          assemName.Name = "TempAssembly";
    
          // Define a dynamic assembly in the current application domain.
          AssemblyBuilder assemBuilder = domain.DefineDynamicAssembly(assemName,
                                                AssemblyBuilderAccess.Run);
    
          // Define a dynamic module in this assembly.
          ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("TempModule");
    
          TypeBuilder b1 = moduleBuilder.DefineType("B", TypeAttributes.Public, typeof(A));
          Console.WriteLine(typeof(A).IsAssignableFrom(b1));
       }
    }
    // The example displays the following output:
    //        True
    
    Imports System.Reflection
    Imports System.Reflection.Emit
    
    Public Class A
    End Class
    
    Module Example
       Public Sub Main()
          Dim domain As AppDomain = AppDomain.CurrentDomain
          Dim assemName As New AssemblyName()
          assemName.Name = "TempAssembly"
    
          ' Define a dynamic assembly in the current application domain.
          Dim assemBuilder As AssemblyBuilder = domain.DefineDynamicAssembly(assemName,
                                                       AssemblyBuilderAccess.Run)
    
          ' Define a dynamic module in this assembly.
          Dim moduleBuilder As ModuleBuilder = assemBuilder.DefineDynamicModule("TempModule")
    
          Dim b1 As TypeBuilder = moduleBuilder.DefineType("B", TypeAttributes.Public, GetType(A))
          Console.WriteLine(GetType(A).IsAssignableFrom(b1))
       End Sub
    End Module
    ' The example displays the following output:
    '       True
    

    Gilt für: