如何:使用反射查询程序集的元数据(LINQ)(Visual Basic)

以下示例演示如何将 LINQ 与反射一起使用,以检索与指定搜索条件匹配的方法的特定元数据。 在这种情况下,查询将查找返回可枚举类型(如数组)的程序集中的所有方法的名称。

示例:

Imports System.Linq
Imports System.Reflection  

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.WriteLine("Press any key to exit... ")  
        Console.ReadKey()  
    End Sub  
End Module  

该示例使用 Assembly.GetTypes 方法来返回指定程序集中类型的数组。 使用Where 子句过滤器,以确保仅返回公共类型。 对于每个公共类型,子查询使用从 MethodInfo 调用返回的 Type.GetMethods 数组生成。 筛选这些结果,仅返回其返回类型为数组或者实现IEnumerable<T>的类型的方法。 最后,这些结果使用类型名称作为键进行分组。

另请参阅