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

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

示例

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();
        }
    }  
}

此示例使用 GetTypes 方法返回指定程序集中的类型的数组。 应用 where 筛选器的目的是只返回公共类型。 对于各个公共类型,将使用从 GetMethods 调用返回的 MethodInfo 数组生成子查询。 这些结果经过筛选,只返回其返回类型为数组或实现 IEnumerable<T> 的其他类型的那些方法。 最后,将类型名称用作键对这些结果进行分组。

编译代码

  • 创建面向 .NET Framework 3.5 版的 Visual Studio 项目。 默认情况下,该项目具有对 System.Core.dll 的引用以及针对 System.Linq 命名空间的 using 指令 (C#) 或 Imports 语句 (Visual Basic)。 在 C# 项目中,添加 System.IO 命名空间的 using 指令。

  • 将此代码复制到您的项目。

  • 按 F5 编译并运行程序。

  • 按任意键退出控制台窗口。

请参见

概念

LINQ to Objects