共用方式為


HOW TO:使用反映查詢組件的中繼資料 (LINQ)

下列範例顯示如何搭配使用 LINQ 與反映 (Reflection),以針對符合所指定搜尋準則的方法,擷取相關的特定中繼資料 (Metadata)。 在這個案例中,查詢會尋找組件 (Assembly) 中所有會傳回可列舉型別 (如陣列) 之方法的名稱。

範例

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 篩選條件以只傳回公用 (Public) 型別。 每種公用型別又使用了 GetMethods 呼叫所傳回的 MethodInfo 陣列來產生子查詢 (Subquery)。 然後會篩選這些結果,以只傳回型別為陣列或其他實作了 IEnumerable<T> 之型別的方法。 最後,就會將型別名稱做為索引鍵來分組這些結果。

編譯程式碼

  • 建立以 .NET Framework 3.5 版為目標的 Visual Studio 專案。 專案預設會含 System.Core.dll 的參考,以及 System.Linq 命名空間 (Namespace) 的 using 指示詞 (C#) 或 Imports 陳述式 (Visual Basic)。 請在 C# 專案中,加入 System.IO 命名空間的 using 指示詞。

  • 將此程式碼複製至您的專案。

  • 按 F5 編譯和執行程式。

  • 按任何鍵離開主控台視窗。

請參閱

概念

LINQ to Objects