Type.GetField Méthode

Définition

Obtient un champ spécifique du Type actuel.

Surcharges

GetField(String)

Recherche le champ public portant le nom spécifié.

GetField(String, BindingFlags)

Recherche le champ spécifié, à l’aide des contraintes de liaison spécifiées.

GetField(String)

Recherche le champ public portant le nom spécifié.

public:
 System::Reflection::FieldInfo ^ GetField(System::String ^ name);
public:
 virtual System::Reflection::FieldInfo ^ GetField(System::String ^ name);
public System.Reflection.FieldInfo? GetField (string name);
public System.Reflection.FieldInfo GetField (string name);
member this.GetField : string -> System.Reflection.FieldInfo
abstract member GetField : string -> System.Reflection.FieldInfo
override this.GetField : string -> System.Reflection.FieldInfo
Public Function GetField (name As String) As FieldInfo

Paramètres

name
String

Chaîne contenant le nom du champ de données à obtenir.

Retours

Objet représentant le champ public avec le nom spécifié, s'il est trouvé ; sinon, null.

Implémente

Exceptions

name a la valeur null.

Cet objet Type est un TypeBuilder dont la méthode CreateType() n’a pas encore été appelée.

Exemples

L’exemple suivant obtient l’objet Type pour la classe spécifiée, obtient l’objet FieldInfo pour le champ et affiche la valeur du champ.

using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyFieldClassA
{
public:
   String^ field;
   MyFieldClassA()
   {
      field = "A Field";
   }


   property String^ Field 
   {
      String^ get()
      {
         return field;
      }

      void set( String^ value )
      {
         if ( field != value )
         {
            field = value;
         }
      }

   }

};

public ref class MyFieldClassB
{
public:
   String^ field;
   MyFieldClassB()
   {
      field = "B Field";
   }


   property String^ Field 
   {
      String^ get()
      {
         return field;
      }

      void set( String^ value )
      {
         if ( field != value )
         {
            field = value;
         }
      }

   }

};

int main()
{
   try
   {
      MyFieldClassB^ myFieldObjectB = gcnew MyFieldClassB;
      MyFieldClassA^ myFieldObjectA = gcnew MyFieldClassA;
      Type^ myTypeA = Type::GetType( "MyFieldClassA" );
      FieldInfo^ myFieldInfo = myTypeA->GetField( "field" );
      Type^ myTypeB = Type::GetType( "MyFieldClassB" );
      FieldInfo^ myFieldInfo1 = myTypeB->GetField( "field", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
      Console::WriteLine( "The value of the field is : {0} ", myFieldInfo->GetValue( myFieldObjectA ) );
      Console::WriteLine( "The value of the field is : {0} ", myFieldInfo1->GetValue( myFieldObjectB ) );
   }
   catch ( SecurityException^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }

}

using System;
using System.Reflection;

public class MyFieldClassA
{
    public string Field = "A Field";
}

public class MyFieldClassB
{
    private string field = "B Field";
    public string Field
    {
        get
        {
            return field;
        }
        set
        {
            if (field!=value)
            {
                field=value;
            }
        }
    }
}

public class MyFieldInfoClass
{
    public static void Main()
    {
        MyFieldClassB myFieldObjectB = new MyFieldClassB();
        MyFieldClassA myFieldObjectA = new MyFieldClassA();

        Type myTypeA = typeof(MyFieldClassA);
        FieldInfo myFieldInfo = myTypeA.GetField("Field");

        Type myTypeB = typeof(MyFieldClassB);
        FieldInfo myFieldInfo1 = myTypeB.GetField("field",
            BindingFlags.NonPublic | BindingFlags.Instance);

        Console.WriteLine("The value of the public field is: '{0}'",
            myFieldInfo.GetValue(myFieldObjectA));
        Console.WriteLine("The value of the private field is: '{0}'",
            myFieldInfo1.GetValue(myFieldObjectB));
    }
}
open System.Reflection

type MyFieldClassA =
    val public Field: string
    new () = { Field = "A Field"}

type MyFieldClassB() =
    let field = "B Field"
    member _.Field
        with get () = field

let myFieldObjectB = MyFieldClassB()
let myFieldObjectA = MyFieldClassA()

let myTypeA = typeof<MyFieldClassA>
let myFieldInfo = myTypeA.GetField "Field"

let myTypeB = typeof<MyFieldClassB>
let myFieldInfo1 = myTypeB.GetField("field", BindingFlags.NonPublic ||| BindingFlags.Instance)

printfn $"The value of the public field is: '{myFieldInfo.GetValue myFieldObjectA}'"
printfn $"The value of the private field is: '{myFieldInfo1.GetValue myFieldObjectB}'"

Imports System.Reflection

Public Class MyFieldClassA
    Public Field As String = "A Field"
End Class

Public Class MyFieldClassB
    Private myField As String = "B Field"

    Public Property Field() As String
        Get
            Return myField
        End Get
        Set(ByVal Value As String)
            If myField <> value Then
                myField = value
            End If
        End Set
    End Property
End Class


Public Class MyFieldInfoClass

    Public Shared Sub Main()
        Dim myFieldObjectB As New MyFieldClassB()
        Dim myFieldObjectA As New MyFieldClassA()

        Dim myTypeA As Type = GetType(MyFieldClassA)
        Dim myFieldInfo As FieldInfo = myTypeA.GetField("Field")

        Dim myTypeB As Type = GetType(MyFieldClassB)
        Dim myFieldInfo1 As FieldInfo = myTypeB.GetField("myField", _
            BindingFlags.NonPublic Or BindingFlags.Instance)

        Console.WriteLine("The value of the public field is: '{0}'", _
            myFieldInfo.GetValue(myFieldObjectA))
        Console.WriteLine("The value of the private field is: '{0}'", _
            myFieldInfo1.GetValue(myFieldObjectB))
    End Sub

End Class

Remarques

La recherche respecte name la casse. La recherche inclut des champs d’instance publique statique et publique.

Si le courant Type représente un type générique construit, cette méthode retourne le FieldInfo avec les paramètres de type remplacés par les arguments de type appropriés.

Si le courant Type représente un paramètre de type dans la définition d’un type générique ou d’une méthode générique, cette méthode recherche les champs de la contrainte de classe.

Voir aussi

S’applique à

GetField(String, BindingFlags)

Recherche le champ spécifié, à l’aide des contraintes de liaison spécifiées.

public:
 abstract System::Reflection::FieldInfo ^ GetField(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
public abstract System.Reflection.FieldInfo? GetField (string name, System.Reflection.BindingFlags bindingAttr);
public abstract System.Reflection.FieldInfo GetField (string name, System.Reflection.BindingFlags bindingAttr);
abstract member GetField : string * System.Reflection.BindingFlags -> System.Reflection.FieldInfo
Public MustOverride Function GetField (name As String, bindingAttr As BindingFlags) As FieldInfo

Paramètres

name
String

Chaîne contenant le nom du champ de données à obtenir.

bindingAttr
BindingFlags

Combinaison de bits de valeurs d’énumération qui spécifie la façon dont est effectuée la recherche.

- ou -

Default pour retourner null.

Retours

Objet représentant le champ qui correspond aux exigences spécifiées, s’il est trouvé ; sinon, null.

Implémente

Exceptions

name a la valeur null.

Exemples

L’exemple suivant obtient l’objet Type pour la classe spécifiée, obtient l’objet FieldInfo pour le champ qui correspond aux indicateurs de liaison spécifiés et affiche la valeur du champ.

using namespace System;
using namespace System::Reflection;
using namespace System::Security;
public ref class MyFieldClassA
{
public:
   String^ field;
   MyFieldClassA()
   {
      field = "A Field";
   }


   property String^ Field 
   {
      String^ get()
      {
         return field;
      }

      void set( String^ value )
      {
         if ( field != value )
         {
            field = value;
         }
      }

   }

};

public ref class MyFieldClassB
{
public:
   String^ field;
   MyFieldClassB()
   {
      field = "B Field";
   }


   property String^ Field 
   {
      String^ get()
      {
         return field;
      }

      void set( String^ value )
      {
         if ( field != value )
         {
            field = value;
         }
      }

   }

};

int main()
{
   try
   {
      MyFieldClassB^ myFieldObjectB = gcnew MyFieldClassB;
      MyFieldClassA^ myFieldObjectA = gcnew MyFieldClassA;
      Type^ myTypeA = Type::GetType( "MyFieldClassA" );
      FieldInfo^ myFieldInfo = myTypeA->GetField( "field" );
      Type^ myTypeB = Type::GetType( "MyFieldClassB" );
      FieldInfo^ myFieldInfo1 = myTypeB->GetField( "field", static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::Instance) );
      Console::WriteLine( "The value of the field is : {0} ", myFieldInfo->GetValue( myFieldObjectA ) );
      Console::WriteLine( "The value of the field is : {0} ", myFieldInfo1->GetValue( myFieldObjectB ) );
   }
   catch ( SecurityException^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception Raised!" );
      Console::WriteLine( "Message : {0}", e->Message );
   }

}

using System;
using System.Reflection;

public class MyFieldClassA
{
    public string Field = "A Field";
}

public class MyFieldClassB
{
    private string field = "B Field";
    public string Field
    {
        get
        {
            return field;
        }
        set
        {
            if (field!=value)
            {
                field=value;
            }
        }
    }
}

public class MyFieldInfoClass
{
    public static void Main()
    {
        MyFieldClassB myFieldObjectB = new MyFieldClassB();
        MyFieldClassA myFieldObjectA = new MyFieldClassA();

        Type myTypeA = typeof(MyFieldClassA);
        FieldInfo myFieldInfo = myTypeA.GetField("Field");

        Type myTypeB = typeof(MyFieldClassB);
        FieldInfo myFieldInfo1 = myTypeB.GetField("field",
            BindingFlags.NonPublic | BindingFlags.Instance);

        Console.WriteLine("The value of the public field is: '{0}'",
            myFieldInfo.GetValue(myFieldObjectA));
        Console.WriteLine("The value of the private field is: '{0}'",
            myFieldInfo1.GetValue(myFieldObjectB));
    }
}
open System.Reflection

type MyFieldClassA =
    val public Field: string
    new () = { Field = "A Field"}

type MyFieldClassB() =
    let field = "B Field"
    member _.Field
        with get () = field

let myFieldObjectB = MyFieldClassB()
let myFieldObjectA = MyFieldClassA()

let myTypeA = typeof<MyFieldClassA>
let myFieldInfo = myTypeA.GetField "Field"

let myTypeB = typeof<MyFieldClassB>
let myFieldInfo1 = myTypeB.GetField("field", BindingFlags.NonPublic ||| BindingFlags.Instance)

printfn $"The value of the public field is: '{myFieldInfo.GetValue myFieldObjectA}'"
printfn $"The value of the private field is: '{myFieldInfo1.GetValue myFieldObjectB}'"

Imports System.Reflection

Public Class MyFieldClassA
    Public Field As String = "A Field"
End Class

Public Class MyFieldClassB
    Private myField As String = "B Field"

    Public Property Field() As String
        Get
            Return myField
        End Get
        Set(ByVal Value As String)
            If myField <> value Then
                myField = value
            End If
        End Set
    End Property
End Class


Public Class MyFieldInfoClass

    Public Shared Sub Main()
        Dim myFieldObjectB As New MyFieldClassB()
        Dim myFieldObjectA As New MyFieldClassA()

        Dim myTypeA As Type = GetType(MyFieldClassA)
        Dim myFieldInfo As FieldInfo = myTypeA.GetField("Field")

        Dim myTypeB As Type = GetType(MyFieldClassB)
        Dim myFieldInfo1 As FieldInfo = myTypeB.GetField("myField", _
            BindingFlags.NonPublic Or BindingFlags.Instance)

        Console.WriteLine("The value of the public field is: '{0}'", _
            myFieldInfo.GetValue(myFieldObjectA))
        Console.WriteLine("The value of the private field is: '{0}'", _
            myFieldInfo1.GetValue(myFieldObjectB))
    End Sub

End Class

Remarques

Le tableau suivant montre quels membres d’une classe de base sont retournés par les méthodes lors de la Get réflexion sur un type.

Type de membre Statique Non statique
Constructeur Non Non
Champ Non Oui. Un champ est toujours masqué par nom et signature.
Événement Non applicable La règle système de type courante est que l’héritage est le même que celui des méthodes qui implémentent la propriété. Reflection traite les propriétés comme masquer par nom et signature. Voir la note 2 ci-dessous.
Méthode Non Oui. Une méthode (virtuelle et non virtuelle) peut être hide-by-name ou hide-by-name-and-signature.
Type imbriqué Non Non
Propriété Non applicable La règle système de type courante est que l’héritage est le même que celui des méthodes qui implémentent la propriété. Reflection traite les propriétés comme masquer par nom et signature. Voir la note 2 ci-dessous.
  1. Masquer par nom et signature prend en compte toutes les parties de la signature, y compris les modificateurs personnalisés, les types de retour, les types de paramètres, les sentinelles et les conventions d’appel non managées. Il s’agit d’une comparaison binaire.

  2. Pour la réflexion, les propriétés et les événements sont masqués par nom-et-signature. Si vous avez une propriété avec un accesseur get et un accesseur set dans la classe de base, mais que la classe dérivée n’a qu’un accesseur get, la propriété de classe dérivée masque la propriété de classe de base et vous ne pourrez pas accéder au setter sur la classe de base.

  3. Les attributs personnalisés ne font pas partie du système de type commun.

Les indicateurs de filtre suivants BindingFlags peuvent être utilisés pour définir les champs à inclure dans la recherche :

  • Vous devez spécifier ou BindingFlags.InstanceBindingFlags.Static pour obtenir un retour.

  • Spécifiez BindingFlags.Public pour inclure des champs publics dans la recherche.

  • Spécifiez BindingFlags.NonPublic pour inclure des champs non publics (c’est-à-dire des champs privés, internes et protégés) dans la recherche.

  • Spécifiez BindingFlags.FlattenHierarchy pour inclure et protected les public membres statiques dans la hiérarchie ; private les membres statiques dans les classes héritées ne sont pas inclus.

Les indicateurs de modification suivants BindingFlags peuvent être utilisés pour modifier le fonctionnement de la recherche :

  • BindingFlags.IgnoreCase pour ignorer le cas de name.

  • BindingFlags.DeclaredOnly pour rechercher uniquement les champs déclarés sur , Typeet non les champs qui ont simplement été hérités.

Consultez la rubrique System.Reflection.BindingFlags (éventuellement en anglais) pour plus d'informations.

Si le courant Type représente un type générique construit, cette méthode retourne le FieldInfo avec les paramètres de type remplacés par les arguments de type appropriés.

Si le courant Type représente un paramètre de type dans la définition d’un type générique ou d’une méthode générique, cette méthode recherche les champs de la contrainte de classe.

Voir aussi

S’applique à