FieldInfo.GetFieldFromHandle FieldInfo.GetFieldFromHandle FieldInfo.GetFieldFromHandle FieldInfo.GetFieldFromHandle Method

Définition

Obtient FieldInfo pour le champ représenté par un handle.Gets a FieldInfo for the field represented by a handle.

Surcharges

GetFieldFromHandle(RuntimeFieldHandle) GetFieldFromHandle(RuntimeFieldHandle) GetFieldFromHandle(RuntimeFieldHandle) GetFieldFromHandle(RuntimeFieldHandle)

Obtient FieldInfo pour le champ représenté par le handle spécifié.Gets a FieldInfo for the field represented by the specified handle.

GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle)

Obtient FieldInfo pour le champ représenté par le handle spécifié, pour le type générique donné.Gets a FieldInfo for the field represented by the specified handle, for the specified generic type.

GetFieldFromHandle(RuntimeFieldHandle) GetFieldFromHandle(RuntimeFieldHandle) GetFieldFromHandle(RuntimeFieldHandle) GetFieldFromHandle(RuntimeFieldHandle)

Obtient FieldInfo pour le champ représenté par le handle spécifié.Gets a FieldInfo for the field represented by the specified handle.

public:
 static System::Reflection::FieldInfo ^ GetFieldFromHandle(RuntimeFieldHandle handle);
public static System.Reflection.FieldInfo GetFieldFromHandle (RuntimeFieldHandle handle);
static member GetFieldFromHandle : RuntimeFieldHandle -> System.Reflection.FieldInfo
Public Shared Function GetFieldFromHandle (handle As RuntimeFieldHandle) As FieldInfo

Paramètres

handle
RuntimeFieldHandle RuntimeFieldHandle RuntimeFieldHandle RuntimeFieldHandle

Structure RuntimeFieldHandle qui contient le handle vers la représentation interne des métadonnées d'un champ.A RuntimeFieldHandle structure that contains the handle to the internal metadata representation of a field.

Retours

Objet FieldInfo représentant le champ spécifié par handle.A FieldInfo object representing the field specified by handle.

Exceptions

handle n'est pas valide.handle is invalid.

Exemples

L’exemple de code suivant utilise Type.GetFields la méthode pour FieldInfo obtenir des objets pour les champs d’un type, RuntimeFieldHandle obtient une structure pour chaque champ, puis récupère les FieldInfo objets des handles à l’aide de cette surcharge de l' GetFieldFromHandleobjetméthode.The following code example uses the Type.GetFields method to get FieldInfo objects for the fields of a type, gets a RuntimeFieldHandle structure for each field, and then retrieves the FieldInfo objects from the handles using this overload of the GetFieldFromHandle method.

using namespace System;
using namespace System::Reflection;

public ref class FieldInfo_GetFieldFromHandle
{
public:
   String^ x;
   Char y;
   float a;
   int b;
};

int main()
{
   // Get the type of the FieldInfo_GetFieldFromHandle class.
   Type^ myType = FieldInfo_GetFieldFromHandle::typeid;

   // Get the fields of the FieldInfo_GetFieldFromHandle class.
   array<FieldInfo^>^myFieldInfoArray = myType->GetFields();
   Console::WriteLine( "\nThe field information of the declared  fields x, y, a, and b is:\n" );
   RuntimeFieldHandle myRuntimeFieldHandle;
   for ( int i = 0; i < myFieldInfoArray->Length; i++ )
   {
      // Get the RuntimeFieldHandle of myFieldInfoArray.
      myRuntimeFieldHandle = myFieldInfoArray[ i ]->FieldHandle;

      // Call the GetFieldFromHandle method. 
      FieldInfo^ myFieldInfo = FieldInfo::GetFieldFromHandle( myRuntimeFieldHandle );

      // Display the FieldInfo of myFieldInfo.
      Console::WriteLine( " {0}", myFieldInfo );
   }
}
using System;
using System.Reflection;

public class FieldInfo_GetFieldFromHandle
{
    public string x;
    public char y;
    public float a;
    public int b;

    public static void Main()
    {
        // Get the type of the FieldInfo_GetFieldFromHandle class.
        Type myType = typeof(FieldInfo_GetFieldFromHandle);
        // Get the fields of the FieldInfo_GetFieldFromHandle class.
        FieldInfo [] myFieldInfoArray = myType.GetFields();
        Console.WriteLine("\nThe field information of the declared" +
            " fields x, y, a, and b is:\n");
        RuntimeFieldHandle myRuntimeFieldHandle;
        for(int i = 0; i < myFieldInfoArray.Length; i++)
        {
            // Get the RuntimeFieldHandle of myFieldInfoArray.
            myRuntimeFieldHandle = myFieldInfoArray[i].FieldHandle;
            // Call the GetFieldFromHandle method. 
            FieldInfo myFieldInfo = FieldInfo.GetFieldFromHandle(myRuntimeFieldHandle);
            // Display the FieldInfo of myFieldInfo.
            Console.WriteLine("{0}", myFieldInfo);
        }
    }
}
Imports System
Imports System.Reflection
Imports Microsoft.VisualBasic

Public Class FieldInfo_GetFieldFromHandle
    Public x As String
    Public y As Char
    Public a As Single
    Public b As Integer

    Public Shared Sub Main()
        ' Get the type of the FieldInfo_GetFieldFromHandle class.
        Dim myType As Type = GetType(FieldInfo_GetFieldFromHandle)
        ' Get the fields of the FieldInfo_GetFieldFromHandle class.
        Dim myFieldInfoArray As FieldInfo() = myType.GetFields()
        Console.WriteLine(ControlChars.NewLine & _
           "The field information of the declared" & _
           " fields x, y, a, and b is:" & ControlChars.NewLine)
        Dim myRuntimeFieldHandle As RuntimeFieldHandle
        Dim i As Integer
        For i = 0 To myFieldInfoArray.Length - 1
            ' Get the RuntimeFieldHandle of myFieldInfoArray.
            myRuntimeFieldHandle = myFieldInfoArray(i).FieldHandle
            ' Call the GetFieldFromHandle method. 
            Dim myFieldInfo As FieldInfo = FieldInfo.GetFieldFromHandle(myRuntimeFieldHandle)
            ' Display the FieldInfo of myFieldInfo.
            Console.WriteLine("{0}", myFieldInfo)
        Next i
    End Sub 'Main
End Class 'FieldInfo_GetFieldFromHandle

Remarques

Les handles ne sont valides que dans le domaine d’application dans lequel ils ont été obtenus.Handles are valid only in the application domain in which they were obtained.

Sécurité

ReflectionPermission
en cas d’appel à liaison tardive via des mécanismes InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])tels que.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Énumération associée : MemberAccess.Associated enumeration: MemberAccess.

GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle)

Obtient FieldInfo pour le champ représenté par le handle spécifié, pour le type générique donné.Gets a FieldInfo for the field represented by the specified handle, for the specified generic type.

public:
 static System::Reflection::FieldInfo ^ GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType);
[System.Runtime.InteropServices.ComVisible(false)]
public static System.Reflection.FieldInfo GetFieldFromHandle (RuntimeFieldHandle handle, RuntimeTypeHandle declaringType);
static member GetFieldFromHandle : RuntimeFieldHandle * RuntimeTypeHandle -> System.Reflection.FieldInfo
Public Shared Function GetFieldFromHandle (handle As RuntimeFieldHandle, declaringType As RuntimeTypeHandle) As FieldInfo

Paramètres

handle
RuntimeFieldHandle RuntimeFieldHandle RuntimeFieldHandle RuntimeFieldHandle

Structure RuntimeFieldHandle qui contient le handle vers la représentation interne des métadonnées d'un champ.A RuntimeFieldHandle structure that contains the handle to the internal metadata representation of a field.

declaringType
RuntimeTypeHandle RuntimeTypeHandle RuntimeTypeHandle RuntimeTypeHandle

Structure RuntimeTypeHandle contenant le handle vers le type générique qui définit le champ.A RuntimeTypeHandle structure that contains the handle to the generic type that defines the field.

Retours

Objet FieldInfo représentant le champ spécifié par handle dans le type générique spécifié par declaringType.A FieldInfo object representing the field specified by handle, in the generic type specified by declaringType.

Exceptions

handle n'est pas valide.handle is invalid.

- ou --or- declaringType n'est pas compatible avec handle.declaringType is not compatible with handle. Par exemple, declaringType est le handle de type runtime de la définition de type générique, et handle vient d'un type construit.For example, declaringType is the runtime type handle of the generic type definition, and handle comes from a constructed type.

Exemples

L’exemple suivant montre comment récupérer FieldInfo des objets pour les champs sur des classes génériques construites.The following example shows how to retrieve FieldInfo objects for fields on constructed generic classes. L’exemple Test<T> définit le type générique (Test(Of T) dans Visual Basic) avec un seul champ nommé TestField, de type. TThe example defines the generic type Test<T> (Test(Of T) in Visual Basic) with a single field named TestField, of type T. L’exemple obtient RuntimeFieldHandle et RuntimeTypeHandle pour le cas où T est String, et illustre les éléments suivants:The example gets the RuntimeFieldHandle and RuntimeTypeHandle for the case where T is String, and demonstrates the following:

  • Une exception est levée si la GetFieldFromHandle(RuntimeFieldHandle) surcharge de méthode est utilisée.An exception is thrown if the GetFieldFromHandle(RuntimeFieldHandle) method overload is used. Cela est vrai même si le champ n’est pas de Ttype.This is true even if the field is not of type T.

  • Un FieldInfo est correctement récupéré si le handle de type au moment de l’exécution est issu de la même construction que le handle Test<string>de champ d’exécution, dans ce cas.A FieldInfo is retrieved successfully if the runtime type handle is from the same construction as the runtime field handle, in this case Test<string>.

  • Si le handle de type au moment de l’exécution provient d’une construction Test<object>compatible, FieldInfo dans ce cas, un pour le champ sur la construction compatible est récupéré.If the runtime type handle is from a compatible construction, in this case Test<object>, a FieldInfo for the field on the compatible construction is retrieved.

  • Si le handle de type au moment de l’exécution ne provient pas d’une construction compatible, une exception est levée.If the runtime type handle is not from a compatible construction, an exception is thrown. Dans ce cas, un type valeur est spécifié pour T.In this case, a value type is specified for T.

using System;
using System.Reflection;

// A generic class with a field whose type is specified by the 
// generic type parameter of the class.
public class Test<T>
{
    public T TestField;
}

public class Example
{
    public static void Main()
    {
        // Get type handles for Test<String> and its field.
        RuntimeTypeHandle rth = typeof(Test<string>).TypeHandle;
        RuntimeFieldHandle rfh = typeof(Test<string>).GetField("TestField").FieldHandle;

        // When a field belongs to a constructed generic type, 
        // such as Test<String>, retrieving the field from the
        // field handle requires the type handle of the constructed
        // generic type. An exception is thrown if the type is not
        // included.
        try
        {
            FieldInfo f1 = FieldInfo.GetFieldFromHandle(rfh);
        }
        catch(Exception ex)
        {
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message);
        }

        // To get the FieldInfo for a field on a generic type, use the
        // overload that specifies the type handle.
        FieldInfo fi = FieldInfo.GetFieldFromHandle(rfh, rth);
        Console.WriteLine("\r\nThe type of {0} is: {1}", fi.Name, fi.FieldType);

        // All constructions of Test<T> for which T is a reference
        // type share the same implementation, so the same runtime 
        // field handle can be used to retrieve the FieldInfo for 
        // TestField on any such construction. Here the runtime field
        // handle is used with Test<Object>.
        fi = FieldInfo.GetFieldFromHandle(rfh, typeof(Test<object>).TypeHandle);
        Console.WriteLine("\r\nThe type of {0} is: {1}", fi.Name, fi.FieldType);

        // Each construction of Test<T> for which T is a value type
        // has its own unique implementation, and an exception is thrown
        // if you supply a constructed type other than the one that 
        // the runtime field handle belongs to.  
        try
        {
            fi = FieldInfo.GetFieldFromHandle(rfh, typeof(Test<int>).TypeHandle);
        }
        catch(Exception ex)
        {
            Console.WriteLine("\r\n{0}: {1}", ex.GetType().Name, ex.Message);
        }
    }
}

/* This code example produces output similar to the following:

ArgumentException: Cannot resolve field TestField because the declaring type of
the field handle Test`1[T] is generic. Explicitly provide the declaring type to
GetFieldFromHandle.

The type of TestField is: System.String

The type of TestField is: System.Object

ArgumentException: Type handle 'Test`1[System.Int32]' and field handle with decl
aring type 'Test`1[System.__Canon]' are incompatible. Get RuntimeFieldHandle and
 declaring RuntimeTypeHandle off the same FieldInfo.
 */
Imports System
Imports System.Reflection

' A generic class with a field whose type is specified by the 
' generic type parameter of the class.
Public Class Test(Of T)
    Public TestField As T 
End Class

Public Class Example

    Public Shared Sub Main()

        ' Get type handles for Test(Of String) and its field.
        Dim rth As RuntimeTypeHandle = _
            GetType(Test(Of String)).TypeHandle
        Dim rfh As RuntimeFieldHandle = _
            GetType(Test(Of String)).GetField("TestField").FieldHandle

        ' When a field belongs to a constructed generic type, 
        ' such as Test(Of String), retrieving the field from the
        ' field handle requires the type handle of the constructed
        ' generic type. An exception is thrown if the type is not
        ' included.
        Try
            Dim f1 As FieldInfo = FieldInfo.GetFieldFromHandle(rfh)
        Catch ex As Exception
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message)
        End Try

        ' To get the FieldInfo for a field on a generic type, use the
        ' overload that specifies the type handle.
        Dim fi As FieldInfo = FieldInfo.GetFieldFromHandle(rfh, rth)
        Console.WriteLine(vbCrLf & "The type of {0} is: {1}", _
            fi.Name, fi.FieldType)

        ' All constructions of Test(Of T) for which T is a reference
        ' type share the same implementation, so the same runtime 
        ' field handle can be used to retrieve the FieldInfo for 
        ' TestField on any such construction. Here the runtime field
        ' handle is used with Test(Of Object).
        fi = FieldInfo.GetFieldFromHandle(rfh, _
                               GetType(Test(Of Object)).TypeHandle)
        Console.WriteLine(vbCrLf & "The type of {0} is: {1}", _
            fi.Name, fi.FieldType)

        ' Each construction of Test(Of T) for which T is a value type
        ' has its own unique implementation, and an exception is thrown
        ' if you supply a constructed type other than the one that 
        ' the runtime field handle belongs to.  
        Try
            fi = FieldInfo.GetFieldFromHandle(rfh, _
                               GetType(Test(Of Integer)).TypeHandle)
        Catch ex As Exception
            Console.WriteLine(vbCrLf & "{0}: {1}", ex.GetType().Name, ex.Message)
        End Try

    End Sub
End Class

' This code example produces output similar to the following:
'
'ArgumentException: Cannot resolve field TestField because the declaring type of
'the field handle Test`1[T] is generic. Explicitly provide the declaring type to
'GetFieldFromHandle.
'
'The type of TestField is: System.String
'
'The type of TestField is: System.Object
'
'ArgumentException: Type handle 'Test`1[System.Int32]' and field handle with decl
'aring type 'Test`1[System.__Canon]' are incompatible. Get RuntimeFieldHandle and
' declaring RuntimeTypeHandle off the same FieldInfo.

Remarques

Les handles ne sont valides que dans le domaine d’application dans lequel ils ont été obtenus.Handles are valid only in the application domain in which they were obtained.

La pratique recommandée est que declaringType doit toujours être le handle de type au moment de l’exécution handle du type construit qui appartient à.The recommended practice is that declaringType should always be the runtime type handle of the constructed type that handle belongs to. Autrement dit, si handle est un handle de champ Runtime pour un champ qui appartient MyType<int> àMyType(Of Integer) (dans Visual Basic) declaringType , est le handle de type MyType<int>au moment de l’exécution pour.That is, if handle is a runtime field handle for a field that belongs to MyType<int> (MyType(Of Integer) in Visual Basic), declaringType is the runtime type handle for MyType<int>. N’utilisez pas le handle de type au moment de l’exécution de la définition de type générique, à moins que le handle de champ d’exécution représente un champ sur la définition de type générique.Do not use the runtime type handle of the generic type definition, unless the runtime field handle represents a field on the generic type definition.

Les implémentations sont compatibles dans certains cas.Implementations are compatible in some cases. Par exemple, une implémentation unique est partagée par tous les types construits à partir d’une définition de type générique particulière à l’aide de types référence pour les arguments de type générique.For example, a single implementation is shared by all types that are constructed from a particular generic type definition by using reference types for the generic type arguments. Par exemple, MyType<string> MyType<object>, et MyType<ArrayList> partagent tous la même implémentation.For example, MyType<string>, MyType<object>, and MyType<ArrayList> all share the same implementation. Dans ce cas, l' FieldInfo objet retourné représente un champ sur le type qui declaringType spécifie, quelle que soit la source d’origine handlede.In this situation, the FieldInfo object that is returned represents a field on the type that declaringType specifies, regardless of the original source of handle. Cette pratique n’est pas recommandée, car elle fonctionne uniquement si les arguments de type générique du type construit sont des types référence.This practice is not recommended, because it works only if the generic type arguments of the constructed type are reference types.

Si un argument générique est un type valeur, le handle de type au moment de l’exécution du type construit n’est pas compatible avec les handles de champ d’exécution des constructions qui ont un type référence dans la même position de paramètre générique ou qui ont un type valeur différent dans cette position .If a generic argument is a value type, the runtime type handle of the constructed type is not compatible with runtime field handles from constructions that have a reference type in the same generic parameter position, or that have a different value type in that position. Dans ce cas, la seule façon d’utiliser la FieldInfo.GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) surcharge est de s’assurer declaringType que est le handle de type au moment de l' handle exécution pour le type construit qui appartient à.In that case, the only way to use the FieldInfo.GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) overload is to ensure that declaringType is the runtime type handle for the constructed type that handle belongs to.

Sécurité

ReflectionPermission
en cas d’appel à liaison tardive via des mécanismes InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])tels que.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Énumération associée : MemberAccess.Associated enumeration: MemberAccess.

S’applique à