Type.GetNestedTypes Metodo

Definizione

Ottiene i tipi annidati all'interno dell'oggetto Type corrente.

Overload

GetNestedTypes()

Restituisce i tipi pubblici annidati all'interno dell'oggetto Type corrente.

GetNestedTypes(BindingFlags)

Quando ne viene eseguito l'override in una classe derivata, cerca i tipi annidati nell'oggetto Type corrente, usando i vincoli di binding specificati.

GetNestedTypes()

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Restituisce i tipi pubblici annidati all'interno dell'oggetto Type corrente.

public:
 cli::array <Type ^> ^ GetNestedTypes();
public:
 virtual cli::array <Type ^> ^ GetNestedTypes();
public Type[] GetNestedTypes ();
member this.GetNestedTypes : unit -> Type[]
abstract member GetNestedTypes : unit -> Type[]
override this.GetNestedTypes : unit -> Type[]
Public Function GetNestedTypes () As Type()

Restituisce

Type[]

Matrice di oggetti Type che rappresenta i tipi pubblici annidati nell'oggetto Type corrente (la ricerca non è ricorsiva), oppure matrice vuota di tipo Type se nessun tipo pubblico è annidato nell'oggetto Type corrente.

Implementazioni

Esempio

Nell'esempio seguente viene definita una classe annidata e un struct in MyClasse quindi vengono ottenuti oggetti dei tipi annidati usando il tipo di MyClass.

using namespace System;
using namespace System::Reflection;
public ref class MyClass
{
public:
   ref class NestClass
   {
      public:
         static int myPublicInt = 0;
   };

   ref struct NestStruct
   {
      public:
         static int myPublicInt = 0;
   };
};

int main()
{
   try
   {
      // Get the Type object corresponding to MyClass.
      Type^ myType = MyClass::typeid;
      
      // Get an array of nested type objects in MyClass.
      array<Type^>^nestType = myType->GetNestedTypes();
      Console::WriteLine( "The number of nested types is {0}.", nestType->Length );
      System::Collections::IEnumerator^ myEnum = nestType->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Type^ t = safe_cast<Type^>(myEnum->Current);
         Console::WriteLine( "Nested type is {0}.", t );
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Error {0}", e->Message );
   }
}
using System;
using System.Reflection;
public class MyClass
{
    public class NestClass
    {
        public static int myPublicInt=0;
    }
    public struct NestStruct
    {
        public static int myPublicInt=0;
    }
}

public class MyMainClass
{
    public static void Main()
    {
        try
        {
            // Get the Type object corresponding to MyClass.
            Type myType=typeof(MyClass);
            // Get an array of nested type objects in MyClass.
            Type[] nestType=myType.GetNestedTypes();
            Console.WriteLine("The number of nested types is {0}.", nestType.Length);
            foreach(Type t in nestType)
                Console.WriteLine("Nested type is {0}.", t.ToString());
        }
        catch(Exception e)
        {
            Console.WriteLine("Error"+e.Message);
        }
    }
}
Imports System.Reflection

Public Class MyClass1
    Public Class NestClass
        Public Shared myPublicInt As Integer = 0
    End Class

    Public Structure NestStruct
        Public myPublicInt As Integer
    End Structure 'NestStruct
End Class

Public Class MyMainClass
    Public Shared Sub Main()
        Try
            ' Get the Type object corresponding to MyClass.
            Dim myType As Type = GetType(MyClass1)
            ' Get an array of nested type objects in MyClass.                 
            Dim nestType As Type() = myType.GetNestedTypes()
            Console.WriteLine("The number of nested types is {0}.", nestType.Length)
            Dim t As Type
            For Each t In nestType
                Console.WriteLine("Nested type is {0}.", t.ToString())
            Next t
        Catch e As Exception
            Console.WriteLine("Error", e.Message.ToString())
        End Try
    End Sub
End Class

Commenti

In .NET 6 e versioni precedenti, il GetNestedTypes metodo non restituisce tipi in un ordine specifico, ad esempio ordine alfabetico o di dichiarazione. Il codice non deve dipendere dall'ordine in cui vengono restituiti i tipi, perché tale ordine varia. Tuttavia, a partire da .NET 7, l'ordinamento è deterministico in base all'ordinamento dei metadati nell'assembly.

Vengono restituiti solo i tipi pubblici annidati immediatamente nel tipo corrente; la ricerca non è ricorsiva.

Nella tabella seguente vengono illustrati i membri di una classe base restituiti dai Get metodi quando si riflette su un tipo.

Tipo di membro Static Non statico
Costruttore No No
Campo No Sì. Un campo è sempre hide-by-name-and-signature.
Evento Non applicabile La regola di sistema dei tipi comune è che l'ereditarietà è uguale a quella dei metodi che implementano la proprietà . La reflection considera le proprietà come hide-by-name-and-signature. Vedere la nota 2 di seguito.
Metodo No Sì. Un metodo (sia virtuale che non virtuale) può essere hide-by-name o hide-by-name-and-signature.
Tipo annidato No No
Proprietà Non applicabile La regola di sistema dei tipi comune è che l'ereditarietà è uguale a quella dei metodi che implementano la proprietà . La reflection considera le proprietà come hide-by-name-and-signature. Vedere la nota 2 di seguito.
  1. Hide-by-name-and-signature considera tutte le parti della firma, inclusi modificatori personalizzati, tipi restituiti, tipi di parametro, sentinel e convenzioni di chiamata non gestite. Si tratta di un confronto binario.

  2. Per la reflection, le proprietà e gli eventi sono hide-by-name-and-signature. Se nella classe base è presente una proprietà con una funzione di accesso get e una funzione di accesso set, ma la classe derivata ha solo una funzione di accesso get, la proprietà della classe derivata nasconde la proprietà della classe base e non sarà possibile accedere al setter nella classe base.

  3. Gli attributi personalizzati non fanno parte del sistema di tipi comuni.

Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo cerca i tipi annidati del vincolo di classe.

Se un tipo annidato è generico, questo metodo restituisce la relativa definizione di tipo generico. Questo vale anche se il tipo generico di inclusione è un tipo costruito chiuso.

Nota

Se l'oggetto corrente Type rappresenta un tipo generico definito in C#, Visual Basic o C++, i relativi tipi annidati sono tutti generici anche se non hanno parametri generici propri. Questo non è necessariamente vero dei tipi annidati definiti negli assembly dinamici o compilati con l'Ilasm.exe assembler IL (IL Assembler).

Per informazioni sui tipi generici annidati e sulla creazione di tipi generici annidati dalle definizioni di tipo generico, vedere MakeGenericType.

Vedi anche

Si applica a

GetNestedTypes(BindingFlags)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Quando ne viene eseguito l'override in una classe derivata, cerca i tipi annidati nell'oggetto Type corrente, usando i vincoli di binding specificati.

public:
 abstract cli::array <Type ^> ^ GetNestedTypes(System::Reflection::BindingFlags bindingAttr);
public abstract Type[] GetNestedTypes (System.Reflection.BindingFlags bindingAttr);
abstract member GetNestedTypes : System.Reflection.BindingFlags -> Type[]
Public MustOverride Function GetNestedTypes (bindingAttr As BindingFlags) As Type()

Parametri

bindingAttr
BindingFlags

Combinazione bit per bit di valori di enumerazione che specifica il modo in cui viene eseguita la ricerca.

-oppure-

Default per restituire null.

Restituisce

Type[]

Matrice di oggetti Type che rappresenta tutti i tipi annidati nell'oggetto Type corrente che corrispondono ai vincoli di binding specificati (la ricerca non è ricorsiva), oppure matrice vuota di tipo Type, se non viene trovato alcun tipo annidato che corrisponde ai vincoli di binding.

Implementazioni

Esempio

Nell'esempio seguente vengono create due classi pubbliche annidate e due classi protette annidate e vengono visualizzate informazioni per le classi che corrispondono ai vincoli di associazione specificati.

using namespace System;
using namespace System::Reflection;

// Create a class with two nested public classes and two nested protected classes.
public ref class MyTypeClass
{
   public:
      ref class Myclass1{};
   
   public:
      ref class Myclass2{};
   
   protected:
      ref class MyClass3{};
   
   protected:
      ref class MyClass4{};
};

void DisplayTypeInfo(array<Type^>^ myArrayType)
{
   // Display the information for all the nested classes.
   for each (Type^ t in myArrayType)
      Console::WriteLine( "The name of the nested class is {0}.", t->FullName);
}

int main()
{
   Type^ myType = MyTypeClass::typeid;
   
   // Get the public nested classes.
   array<Type^>^myTypeArray = myType->GetNestedTypes( static_cast<BindingFlags>(BindingFlags::Public));
   Console::WriteLine( "The number of nested public classes is {0}.", myTypeArray->Length );
  
   // Display all the public nested classes.
   DisplayTypeInfo( myTypeArray );
   Console::WriteLine();
   
   // Get the nonpublic nested classes.
   array<Type^>^myTypeArray1 = myType->GetNestedTypes( static_cast<BindingFlags>(BindingFlags::NonPublic));
   Console::WriteLine( "The number of nested protected classes is {0}.", myTypeArray1->Length );
   
   // Display all the nonpublic nested classes.
   DisplayTypeInfo( myTypeArray1 );
}
// The example displays the following output:
//       The number of public nested classes is 2.
//       The name of the nested class is MyTypeClass+Myclass1.
//       The name of the nested class is MyTypeClass+Myclass2.
//       
//       The number of protected nested classes is 2.
//       The name of the nested class is MyTypeClass+MyClass3.
//       The name of the nested class is MyTypeClass+MyClass4.
using System;
using System.Reflection;

// Create a class with 2 nested public and 2 nested protected classes.
public class MyTypeClass
{
    public class Myclass1
    {
    }

    public class Myclass2
    {
    }

    protected class MyClass3
    {
    }

    protected class MyClass4
    {
    }
}

public class TypeMain
{
    public static void Main()
    {
        Type myType = (typeof(MyTypeClass));
        // Get the public nested classes.
        Type[] myTypeArray = myType.GetNestedTypes(BindingFlags.Public);
        Console.WriteLine("The number of nested public classes is {0}.", myTypeArray.Length);
        // Display all the public nested classes.
        DisplayTypeInfo(myTypeArray);
        Console.WriteLine();

        // Get the nonpublic nested classes.
        Type[] myTypeArray1 = myType.GetNestedTypes(BindingFlags.NonPublic|BindingFlags.Instance);
        Console.WriteLine("The number of nested protected classes is {0}.", myTypeArray1.Length);
        // Display all the nonpublic nested classes.
        DisplayTypeInfo(myTypeArray1);		
    }

    public static void DisplayTypeInfo(Type[] myArrayType)
    {
        // Display the information for all the nested classes.
        foreach (var t in myArrayType)
            Console.WriteLine("The name of the nested class is {0}.", t.FullName);
    }
}
// The example displays the following output:
//       The number of public nested classes is 2.
//       The name of the nested class is MyTypeClass+Myclass1.
//       The name of the nested class is MyTypeClass+Myclass2.
//
//       The number of protected nested classes is 2.
//       The name of the nested class is MyTypeClass+MyClass3.
//       The name of the nested class is MyTypeClass+MyClass4.
Imports System.Reflection

' Create a class with three properties.
Public Class MyTypeClass
    Public Class Myclass1
    End Class 

    Public Class Myclass2
    End Class 

    Protected Class MyClass3
    End Class 

    Protected Class MyClass4
    End Class 
End Class 

Public Class TypeMain
    Public Shared Sub Main()
        Dim myType As Type = GetType(MyTypeClass)

        ' Get the public nested classes.
        Dim myTypeArray As Type() = myType.GetNestedTypes((BindingFlags.Public))
        Console.WriteLine("The number of public nested classes is {0}.", myTypeArray.Length.ToString())
        ' Display all the public nested classes.
        DisplayTypeInfo(myTypeArray)
        Console.WriteLine()
        
        ' Get the nonpublic nested classes.
        Dim myTypeArray1 As Type() = myType.GetNestedTypes((BindingFlags.NonPublic))
        Console.WriteLine("The number of protected nested classes is {0}.", myTypeArray1.Length.ToString())
        ' Display  the information for all nested classes.
        DisplayTypeInfo(myTypeArray1)
    End Sub 

    Public Shared Sub DisplayTypeInfo(ByVal myArrayType() As Type)
        ' Display the information for all nested classes.
        For Each t In myArrayType
            Console.WriteLine("The name of the nested class is {0}.", t.FullName)
        Next 
    End Sub 
End Class  
' The example displays the following output:
'       The number of public nested classes is 2.
'       The name of the nested class is MyTypeClass+Myclass1.
'       The name of the nested class is MyTypeClass+Myclass2.
'       
'       The number of protected nested classes is 2.
'       The name of the nested class is MyTypeClass+MyClass3.
'       The name of the nested class is MyTypeClass+MyClass4.

Commenti

La ricerca di tipi annidati non è ricorsiva.

In .NET 6 e versioni precedenti, il GetNestedTypes metodo non restituisce tipi in un ordine specifico, ad esempio ordine alfabetico o di dichiarazione. Il codice non deve dipendere dall'ordine in cui vengono restituiti i tipi, perché tale ordine varia. Tuttavia, a partire da .NET 7, l'ordinamento è deterministico in base all'ordinamento dei metadati nell'assembly.

I flag di filtro seguenti BindingFlags possono essere usati per definire i tipi annidati da includere nella ricerca:

Questo metodo restituisce solo i tipi annidati del tipo corrente. Non esegue ricerche nelle classi di base del tipo corrente. Per trovare i tipi annidati nelle classi di base, è necessario esaminare la gerarchia di ereditarietà, chiamando GetNestedTypes a ogni livello.

BindingFlags.Instance e BindingFlags.Static vengono ignorati.

La chiamata a questo metodo con solo il BindingFlags.Public flag o solo il BindingFlags.NonPublic flag restituirà i tipi annidati specificati e non richiede altri flag.

Per altre informazioni, vedere System.Reflection.BindingFlags.

Se l'oggetto corrente Type rappresenta un parametro di tipo nella definizione di un tipo generico o di un metodo generico, questo metodo cerca i tipi annidati del vincolo di classe.

Se un tipo annidato è generico, questo metodo restituisce la relativa definizione di tipo generico. Questo vale anche se il tipo generico di inclusione è un tipo costruito chiuso.

Nota

Se l'oggetto corrente Type rappresenta un tipo generico definito in C#, Visual Basic o C++, i relativi tipi annidati sono tutti generici anche se non hanno parametri generici propri. Questo non è necessariamente vero dei tipi annidati definiti negli assembly dinamici o compilati con l'Ilasm.exe assembler IL (IL Assembler).

Per informazioni sui tipi generici annidati e sulla creazione di tipi generici annidati dalle definizioni di tipo generico, vedere MakeGenericType.

Vedi anche

Si applica a