Condividi tramite


Procedura: eseguire una query sui metadati di un assembly tramite reflection (LINQ)

Nell'esempio seguente viene illustrato come utilizzare LINQ con la reflection per recuperare metadati specifici sui metodi che corrispondono a un criterio di ricerca specificato. In questo caso, la query cercherà i nomi di tutti i metodi nell'assembly che restituiscono tipi enumerabili, ad esempio matrici.

Esempio

Imports System.Reflection
Imports System.IO
Imports System.Linq
Module Module1

    Sub Main()
        Dim asmbly As Assembly = 
            Assembly.Load("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken= b77a5c561934e089")

        Dim pubTypesQuery = From type In asmbly.GetTypes() 
                            Where type.IsPublic 
                            From method In type.GetMethods() 
                            Where method.ReturnType.IsArray = True 
                            Let name = method.ToString() 
                            Let typeName = type.ToString() 
                            Group name By typeName Into methodNames = Group


        Console.WriteLine("Getting ready to iterate")
        For Each item In pubTypesQuery
            Console.WriteLine(item.methodNames)

            For Each type In item.methodNames
                Console.WriteLine(" " & type)
            Next
        Next
        Console.ReadKey()
    End Sub

End Module
using System.Reflection;
using System.IO;
namespace LINQReflection
{
    class ReflectionHowTO
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.Load("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken= b77a5c561934e089");
            var pubTypesQuery = from type in assembly.GetTypes()
                        where type.IsPublic
                            from method in type.GetMethods()
                            where method.ReturnType.IsArray == true 
                                || ( method.ReturnType.GetInterface(
                                    typeof(System.Collections.Generic.IEnumerable<>).FullName ) != null
                                && method.ReturnType.FullName != "System.String" )
                            group method.ToString() by type.ToString();

            foreach (var groupOfMethods in pubTypesQuery)
            {
                Console.WriteLine("Type: {0}", groupOfMethods.Key);
                foreach (var method in groupOfMethods)
                {
                    Console.WriteLine("  {0}", method);
                }
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }  
}

Il seguente esempio utilizza il metodo GetTypes per restituire una matrice di tipi nell'assembly specificato. Viene applicato il filtro where in modo che vengano restituiti solo tipi pubblici. Per ogni tipo pubblico, viene generata una sottoquery utilizzando la matrice MethodInfo restituita dalla chiamata GetMethods. Questi risultati vengono filtrati per restituire solo i metodi il cui tipo restituito sia una matrice o in alternativa un tipo che implementa IEnumerable<T>. Infine, questi risultati vengono raggruppati utilizzando il nome del tipo come chiave.

Compilazione del codice

  • Creare un progetto Visual Studio per .NET Framework versione 3.5. Per impostazione predefinita, il progetto include un riferimento a System.Core.dll e una direttiva using (C#) o un'istruzione Imports (Visual Basic) per lo spazio dei nomi System.Linq. Nei progetti C# aggiungere una direttiva using per lo spazio dei nomi System.IO.

  • Copiare questo codice nel progetto.

  • Premere F5 per compilare ed eseguire il programma.

  • Premere un tasto per chiudere la finestra della console.

Vedere anche

Concetti

LINQ to Objects