Breyta

Deila með


Type.GetFields Method

Definition

Gets the fields of the current Type.

Overloads

GetFields()

Returns all the public fields of the current Type.

GetFields(BindingFlags)

When overridden in a derived class, searches for the fields defined for the current Type, using the specified binding constraints.

GetFields()

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Returns all the public fields of the current Type.

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

Returns

An array of FieldInfo objects representing all the public fields defined for the current Type.

-or-

An empty array of type FieldInfo, if no public fields are defined for the current Type.

Implements

Examples

The following example shows a use of the GetFields() method.

#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

Remarks

In .NET 6 and earlier versions, the GetFields method does not return fields in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which fields are returned, because that order varies. However, starting with .NET 7, the ordering is deterministic based upon the metadata ordering in the assembly.

The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

Member Type Static Non-Static
Constructor No No
Field No Yes. A field is always hide-by-name-and-signature.
Event Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
Method No Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
Nested Type No No
Property Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.

  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. Custom attributes are not part of the common type system.

If the current Type represents a constructed generic type, this method returns the FieldInfo objects with the type parameters replaced by the appropriate type arguments.

If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the public fields of the class constraint.

See also

Applies to

GetFields(BindingFlags)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

When overridden in a derived class, searches for the fields defined for the current Type, using the specified binding constraints.

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

Parameters

bindingAttr
BindingFlags

A bitwise combination of the enumeration values that specify how the search is conducted.

-or-

Default to return an empty array.

Returns

An array of FieldInfo objects representing all fields defined for the current Type that match the specified binding constraints.

-or-

An empty array of type FieldInfo, if no fields are defined for the current Type, or if none of the defined fields match the binding constraints.

Implements

Examples

The following example shows a use of the GetFields(BindingFlags) method.

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

Remarks

For the GetFields(BindingFlags) overload to successfully retrieve property information, the bindingAttr argument must include at least one of BindingFlags.Instance and BindingFlags.Static, along with at least one of BindingFlags.NonPublic and BindingFlags.Public.

The following BindingFlags filter flags can be used to define which fields to include in the search:

  • Specify BindingFlags.Instance to include instance methods.

  • Specify BindingFlags.Static to include static methods.

  • Specify BindingFlags.Public to include public fields in the search.

  • Specify BindingFlags.NonPublic to include non-public fields (that is, private, internal, and protected fields) in the search. Only protected and internal fields on base classes are returned; private fields on base classes are not returned.

  • Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

  • Specify BindingFlags.Default alone to return an empty PropertyInfo array.

The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.DeclaredOnly to search only the fields declared on the Type, not fields that were simply inherited.

See System.Reflection.BindingFlags for more information.

In .NET 6 and earlier versions, the GetFields method does not return fields in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which fields are returned, because that order varies. However, starting with .NET 7, the ordering is deterministic based upon the metadata ordering in the assembly.

If the current Type represents a constructed generic type, this method returns the FieldInfo objects with the type parameters replaced by the appropriate type arguments.

If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the public fields of the class constraint.

See also

Applies to