代码改变世界

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

2013-01-29 22:32  yezhi  阅读(259)  评论(0)    收藏  举报
下面的示例演示 LINQ 如何与反射一起用于检索有关与指定的搜索条件相匹配的方法的特定元数据。 在本例中,查询将查找程序集中返回可枚举的类型(如数组)的所有方法的名称。

示例
C#VB

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> 的其他类型的那些方法。 最后,将类型名称用作键对这些结果进行分组。

http://msdn.microsoft.com/zh-cn/library/vstudio/bb546150.aspx