Type.GetFields Metoda

Definicja

Pobiera pola bieżącego Typeelementu .

Przeciążenia

GetFields()

Zwraca wszystkie pola publiczne bieżącego Typeelementu .

GetFields(BindingFlags)

Po zastąpieniu w klasie pochodnej wyszukuje pola zdefiniowane dla bieżącego Typeelementu przy użyciu określonych ograniczeń powiązania.

GetFields()

Zwraca wszystkie pola publiczne bieżącego Typeelementu .

public:
 cli::array <System::Reflection::FieldInfo ^> ^ GetFields();
public:
 virtual cli::array <System::Reflection::FieldInfo ^> ^ GetFields();
public System.Reflection.FieldInfo[] GetFields ();
member this.GetFields : unit -> System.Reflection.FieldInfo[]
abstract member GetFields : unit -> System.Reflection.FieldInfo[]
override this.GetFields : unit -> System.Reflection.FieldInfo[]
Public Function GetFields () As FieldInfo()

Zwraca

Tablica FieldInfo obiektów reprezentujących wszystkie pola publiczne zdefiniowane dla bieżącego Typeobiektu .

-lub-

Pusta tablica typu FieldInfo, jeśli dla bieżącego elementu Typenie zdefiniowano żadnych pól publicznych.

Implementuje

Przykłady

W poniższym przykładzie pokazano użycie GetFields() metody .

#using <system.dll>

using namespace System;
using namespace System::Reflection;
using namespace System::ComponentModel::Design;

int main()
{
   try
   {
      // Get the type handle of a specified class.
      Type^ myType = ViewTechnology::typeid;

      // Get the fields of the specified class.
      array<FieldInfo^>^myField = myType->GetFields();
      Console::WriteLine( "\nDisplaying fields that have SpecialName attributes:\n" );
      for ( int i = 0; i < myField->Length; i++ )
      {
         // Determine whether or not each field is a special name.
         if ( myField[ i ]->IsSpecialName )
         {
            Console::WriteLine( "The field {0} has a SpecialName attribute.", myField[ i ]->Name );
         }
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception : {0} ", e->Message );
   }
}
using System;
using System.Reflection;
using System.ComponentModel.Design;

class FieldInfo_IsSpecialName
{
    public static void Main()
    {
        try
        {
            // Get the type handle of a specified class.
            Type myType = typeof(ViewTechnology);

            // Get the fields of the specified class.
            FieldInfo[] myField = myType.GetFields();

            Console.WriteLine("\nDisplaying fields that have SpecialName attributes:\n");
            for(int i = 0; i < myField.Length; i++)
            {
                // Determine whether or not each field is a special name.
                if(myField[i].IsSpecialName)
                {
                    Console.WriteLine("The field {0} has a SpecialName attribute.",
                        myField[i].Name);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception : {0} " , e.Message);
        }
    }
}
open System.ComponentModel.Design

try
    // Get the type handle of a specified class.
    let myType = typeof<ViewTechnology>

    // Get the fields of the specified class.
    let myFields = myType.GetFields()

    printfn $"\nDisplaying fields that have SpecialName attributes:\n"
    for field in myFields do
        // Determine whether or not each field is a special name.
        if field.IsSpecialName then
            printfn $"The field {field.Name} has a SpecialName attribute."
with e ->
    printfn $"Exception : {e.Message} "
Imports System.Reflection
Imports System.ComponentModel.Design

Class FieldInfo_IsSpecialName

    Public Shared Sub Main()
        Try
            ' Get the type handle of a specified class.
            Dim myType As Type = GetType(ViewTechnology)

            ' Get the fields of a specified class.
            Dim myField As FieldInfo() = myType.GetFields()

            Console.WriteLine(ControlChars.Cr + "Displaying fields that have SpecialName attributes:" + ControlChars.Cr)
            Dim i As Integer
            For i = 0 To myField.Length - 1
                ' Determine whether or not each field is a special name.
                If myField(i).IsSpecialName Then
                    Console.WriteLine("The field {0} has a SpecialName attribute.", myField(i).Name)
                End If
            Next i
        Catch e As Exception
            Console.WriteLine("Exception : {0} ", e.Message.ToString())
        End Try
    End Sub
End Class

Uwagi

Metoda GetFields nie zwraca pól w określonej kolejności, takich jak kolejność alfabetyczna lub deklaracja. Kod nie może zależeć od kolejności zwracania pól, ponieważ ta kolejność jest różna.

W poniższej tabeli przedstawiono, które elementy członkowskie klasy bazowej są zwracane przez Get metody podczas odzwierciedlania typu.

Typ elementu członkowskiego Static Niestatyczna
Konstruktor Nie Nie
Pole Nie Tak. Pole jest zawsze ukryte przez nazwę i podpis.
Zdarzenie Nie dotyczy Zasadą systemu typu jest to, że dziedziczenie jest takie samo, jak w przypadku metod, które implementują właściwość. Odbicie traktuje właściwości jako ukryte przez nazwę i podpis. Patrz Uwaga 2 poniżej.
Metoda Nie Tak. Metodą (zarówno wirtualną, jak i niewirtualną) może być ukrycie przez nazwę lub przez nazwę i podpis.
Typu zagnieżdżony Nie Nie
Właściwość Nie dotyczy Zasadą systemu typu jest to, że dziedziczenie jest takie samo, jak w przypadku metod, które implementują właściwość. Odbicie traktuje właściwości jako ukryte przez nazwę i podpis. Patrz Uwaga 2 poniżej.
  1. Ukrycie przez nazwę i podpis dotyczy wszystkich części podpisu, w tym modyfikatorów niestandardowych, zwraca typy, typy parametrów, wartowników i niezarządzane konwencje wywoływania. To jest porównanie binarne.

  2. W celu odbicia właściwości i zdarzenia są ukrywane przez nazwę i podpis. Jeśli istnieje właściwość z akcesorem pobierania i ustawiania w klasie bazowej, ale odziedziczona klasa ma tylko akcesor pobierania, właściwość klasy odziedziczonej ukrywa właściwości klasy bazowej, a nie można uzyskać dostępu do metody ustawiającej w klasie bazowej.

  3. Atrybuty niestandardowe nie są częścią wspólnego typu systemowego.

Jeśli bieżący Type reprezentuje skonstruowany typ ogólny, ta metoda zwraca FieldInfo obiekty z parametrami typu zastąpionymi przez odpowiednie argumenty typu.

Jeśli bieżący Type reprezentuje parametr typu w definicji typu ogólnego lub metody ogólnej, ta metoda przeszukuje pola publiczne ograniczenia klasy.

Zobacz też

Dotyczy

GetFields(BindingFlags)

Po zastąpieniu w klasie pochodnej wyszukuje pola zdefiniowane dla bieżącego Typeelementu przy użyciu określonych ograniczeń powiązania.

public:
 abstract cli::array <System::Reflection::FieldInfo ^> ^ GetFields(System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.FieldInfo[] GetFields (System.Reflection.BindingFlags bindingAttr);
abstract member GetFields : System.Reflection.BindingFlags -> System.Reflection.FieldInfo[]
Public MustOverride Function GetFields (bindingAttr As BindingFlags) As FieldInfo()

Parametry

bindingAttr
BindingFlags

Bitowa kombinacja wartości wyliczenia, które określają sposób przeprowadzania wyszukiwania.

-lub-

Default aby zwrócić pustą tablicę.

Zwraca

Tablica FieldInfo obiektów reprezentujących wszystkie pola zdefiniowane dla bieżącego Type , które są zgodne z określonymi ograniczeniami powiązania.

-lub-

Pusta tablica typu FieldInfo, jeśli żadne pola nie są zdefiniowane dla bieżącego Typeobiektu , lub jeśli żadne ze zdefiniowanych pól nie pasuje do ograniczeń powiązania.

Implementuje

Przykłady

W poniższym przykładzie pokazano użycie GetFields(BindingFlags) metody .

using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::InteropServices;
public ref class AttributesSample
{
public:
   void Mymethod( int int1m, [Out]interior_ptr<String^> str2m, interior_ptr<String^> str3m )
   {
       *str2m = "in Mymethod";
   }
};

void PrintAttributes( Type^ attribType, int iAttribValue )
{
   if (  !attribType->IsEnum )
   {
      Console::WriteLine( "This type is not an enum." );
      return;
   }

   array<FieldInfo^>^fields = attribType->GetFields( static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Static) );
   for ( int i = 0; i < fields->Length; i++ )
   {
      int fieldvalue = safe_cast<Int32>(fields[ i ]->GetValue( nullptr ));
      if ( (fieldvalue & iAttribValue) == fieldvalue )
      {
         Console::WriteLine( fields[ i ]->Name );
      }
   }
}

int main()
{
   Console::WriteLine( "Reflection.MethodBase.Attributes Sample" );

   // Get the type.
   Type^ MyType = Type::GetType( "AttributesSample" );

   // Get the method Mymethod on the type.
   MethodBase^ Mymethodbase = MyType->GetMethod( "Mymethod" );

   // Display the method name.
   Console::WriteLine( "Mymethodbase = {0}", Mymethodbase );

   // Get the MethodAttribute enumerated value.
   MethodAttributes Myattributes = Mymethodbase->Attributes;

   // Display the flags that are set.
   PrintAttributes( System::Reflection::MethodAttributes::typeid, (int)Myattributes );
   return 0;
}

using System;
using System.Reflection;

class AttributesSample
{
    public void Mymethod (int int1m, out string str2m, ref string str3m)
    {
        str2m = "in Mymethod";
    }

    public static int Main(string[] args)
    {
        Console.WriteLine ("Reflection.MethodBase.Attributes Sample");

        // Get the type.
        Type MyType = Type.GetType("AttributesSample");

        // Get the method Mymethod on the type.
        MethodBase Mymethodbase = MyType.GetMethod("Mymethod");

        // Display the method name.
        Console.WriteLine("Mymethodbase = " + Mymethodbase);

        // Get the MethodAttribute enumerated value.
        MethodAttributes Myattributes = Mymethodbase.Attributes;

        // Display the flags that are set.
        PrintAttributes(typeof(System.Reflection.MethodAttributes), (int) Myattributes);
        return 0;
    }

    public static void PrintAttributes(Type attribType, int iAttribValue)
    {
        if (!attribType.IsEnum)
        {
            Console.WriteLine("This type is not an enum.");
            return;
        }

        FieldInfo[] fields = attribType.GetFields(BindingFlags.Public | BindingFlags.Static);
        for (int i = 0; i < fields.Length; i++)
        {
            int fieldvalue = (int)fields[i].GetValue(null);
            if ((fieldvalue & iAttribValue) == fieldvalue)
            {
                Console.WriteLine(fields[i].Name);
            }
        }
    }
}
open System
open System.Reflection

type AttributesSample() =
    member _.Mymethod(int1m: int, str2m: string outref, str3m: string byref) =
        str2m <- "in Mymethod"

let printAttributes (attribType: Type) iAttribValue =
    if not attribType.IsEnum then
        printfn "This type is not an enum."
    else
        let fields = attribType.GetFields(BindingFlags.Public ||| BindingFlags.Static)
        for f in fields do
            let fieldvalue = f.GetValue null :?> int
            if fieldvalue &&& iAttribValue = fieldvalue then
                printfn $"{f.Name}"

printfn "Reflection.MethodBase.Attributes Sample"

// Get the type.
let MyType = Type.GetType "AttributesSample"

// Get the method Mymethod on the type.
let Mymethodbase = MyType.GetMethod "Mymethod"

// Display the method name.
printfn $"Mymethodbase = {Mymethodbase}"

// Get the MethodAttribute enumerated value.
let Myattributes = Mymethodbase.Attributes

// Display the flags that are set.
printAttributes typeof<MethodAttributes> (int Myattributes)
Imports System.Reflection

Class AttributesSample

    Public Sub Mymethod(ByVal int1m As Integer, ByRef str2m As String, ByRef str3m As String)
        str2m = "in Mymethod"
    End Sub

    Public Shared Function Main(ByVal args() As String) As Integer
        Console.WriteLine("Reflection.MethodBase.Attributes Sample")

        ' Get the type.
        Dim MyType As Type = Type.GetType("AttributesSample")

        ' Get the method Mymethod on the type.
        Dim Mymethodbase As MethodBase = MyType.GetMethod("Mymethod")

        ' Display the method name.
        Console.WriteLine("Mymethodbase = {0}.", Mymethodbase)

        ' Get the MethodAttribute enumerated value.
        Dim Myattributes As MethodAttributes = Mymethodbase.Attributes

        ' Display the flags that are set.
        PrintAttributes(GetType(System.Reflection.MethodAttributes), CInt(Myattributes))
        Return 0
    End Function 'Main

    Public Shared Sub PrintAttributes(ByVal attribType As Type, ByVal iAttribValue As Integer)
        If Not attribType.IsEnum Then
            Console.WriteLine("This type is not an enum.")
            Return
        End If
        Dim fields As FieldInfo() = attribType.GetFields((BindingFlags.Public Or BindingFlags.Static))
        Dim i As Integer
        For i = 0 To fields.Length - 1
            Dim fieldvalue As Integer = CType(fields(i).GetValue(Nothing), Int32)
            If (fieldvalue And iAttribValue) = fieldvalue Then
                Console.WriteLine(fields(i).Name)
            End If
        Next i
    End Sub
End Class

Uwagi

GetFields(BindingFlags) Aby przeciążenie mogło pomyślnie pobrać informacje o właściwości, bindingAttr argument musi zawierać co najmniej jedną z BindingFlags.Instance wartości i BindingFlags.Staticoraz co najmniej jedną z BindingFlags.NonPublic wartości i BindingFlags.Public.

Następujące BindingFlags flagi filtru mogą służyć do definiowania pól do uwzględnienia w wyszukiwaniu:

  • Określ BindingFlags.Instance , aby uwzględnić metody wystąpienia.

  • Określ BindingFlags.Static , aby uwzględnić metody statyczne.

  • Określ BindingFlags.Public , aby uwzględnić pola publiczne w wyszukiwaniu.

  • Określ BindingFlags.NonPublic , aby uwzględnić pola inne niż publiczne (czyli pola prywatne, wewnętrzne i chronione) w wyszukiwaniu. Zwracane są tylko pola chronione i wewnętrzne w klasach bazowych; pola prywatne w klasach bazowych nie są zwracane.

  • Określ BindingFlags.FlattenHierarchy , aby uwzględnić public i protected statyczne elementy członkowskie w hierarchii; private statyczne elementy członkowskie w klasach dziedziczynych nie są uwzględniane.

  • Określ BindingFlags.Default sam, aby zwrócić pustą PropertyInfo tablicę.

Następujące BindingFlags flagi modyfikatora mogą służyć do zmiany sposobu działania wyszukiwania:

  • BindingFlags.DeclaredOnly aby wyszukać tylko pola zadeklarowane w obiekcie Type, a nie pola, które zostały po prostu odziedziczone.

Aby uzyskać więcej informacji, zobacz System.Reflection.BindingFlags.

Metoda GetFields nie zwraca pól w określonej kolejności, takich jak kolejność alfabetyczna lub deklaracja. Kod nie może zależeć od kolejności zwracania pól, ponieważ ta kolejność jest różna.

Jeśli bieżący Type reprezentuje skonstruowany typ ogólny, ta metoda zwraca FieldInfo obiekty z parametrami typu zastąpionymi przez odpowiednie argumenty typu.

Jeśli bieżący Type reprezentuje parametr typu w definicji typu ogólnego lub metody ogólnej, ta metoda przeszukuje pola publiczne ograniczenia klasy.

Zobacz też

Dotyczy