如何:使用反射获取类型和成员信息

System.Reflection 命名空间包含许多获取关于类型及其成员的信息的方法。 本文介绍其中一种方法:Type.GetMembers。 有关其他信息,请参阅反射概述

示例

下例演示通过使用反射获取类型和成员信息:

using namespace System;
using namespace System::Reflection;

ref class Asminfo1
{
public:
    static void Main()
    {
        Console::WriteLine ("\nReflection.MemberInfo");

        // Get the Type and MemberInfo.
        // Insert the fully qualified class name inside the quotation marks in the
        // following statement.
        Type^ MyType = Type::GetType("System.IO.BinaryReader");
        array<MemberInfo^>^ Mymemberinfoarray = MyType->GetMembers(BindingFlags::Public |
            BindingFlags::NonPublic | BindingFlags::Static |
            BindingFlags::Instance | BindingFlags::DeclaredOnly);

        // Get and display the DeclaringType method.
        Console::Write($"\nThere are {Mymemberinfoarray->Length} documentable members in ");
        Console::Write($"{MyType->FullName}.");

        for each (MemberInfo^ Mymemberinfo in Mymemberinfoarray)
        {
            Console::Write("\n" + Mymemberinfo->Name);
        }
    }
};

int main()
{
    Asminfo1::Main();
}
using System;
using System.Reflection;

class Asminfo1
{
    public static void Main()
    {
        Console.WriteLine ("\nReflection.MemberInfo");

        // Get the Type and MemberInfo.
        // Insert the fully qualified class name inside the quotation marks in the
        // following statement.
        Type MyType = Type.GetType("System.IO.BinaryReader");
        MemberInfo[] Mymemberinfoarray = MyType.GetMembers(BindingFlags.Public |
            BindingFlags.NonPublic | BindingFlags.Static |
            BindingFlags.Instance | BindingFlags.DeclaredOnly);

        // Get and display the DeclaringType method.
        Console.Write($"\nThere are {Mymemberinfoarray.Length} documentable members in ");
        Console.Write($"{MyType.FullName}.");

        foreach (MemberInfo Mymemberinfo in Mymemberinfoarray)
        {
            Console.Write("\n" + Mymemberinfo.Name);
        }
    }
}
Imports System.Reflection

Class Asminfo1
    Public Shared Sub Main()
        Console.WriteLine("\nReflection.MemberInfo")

        ' Get the Type and MemberInfo.
        ' Insert the fully qualified class name inside the quotation marks in the
        ' following statement.
        Dim MyType As Type = Type.GetType("System.IO.BinaryReader")
        Dim Mymemberinfoarray() As MemberInfo = MyType.GetMembers(BindingFlags.Public Or
            BindingFlags.NonPublic Or BindingFlags.Static Or
            BindingFlags.Instance Or BindingFlags.DeclaredOnly)

        ' Get and display the DeclaringType method.
        Console.Write($"\nThere are {Mymemberinfoarray.Length} documentable members in ")
        Console.Write($"{MyType.FullName}.")

        For Each Mymemberinfo As MemberInfo in Mymemberinfoarray
            Console.Write("\n" + Mymemberinfo.Name)
        Next
    End Sub
End Class

另请参阅