FieldInfo.GetFieldFromHandle Método

Definición

Obtiene FieldInfo para el campo representado por un identificador.

Sobrecargas

GetFieldFromHandle(RuntimeFieldHandle)

Obtiene FieldInfo para el campo representado por el identificador especificado.

GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle)

Obtiene FieldInfo para el campo representado por el identificador especificado, para el tipo genérico especificado.

GetFieldFromHandle(RuntimeFieldHandle)

Obtiene FieldInfo para el campo representado por el identificador especificado.

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

Parámetros

handle
RuntimeFieldHandle

Estructura RuntimeFieldHandle que contiene el identificador para la representación interna de los metadatos de un campo.

Devoluciones

FieldInfo

Objeto FieldInfo que representa el campo especificado por handle.

Excepciones

handle no es válido.

Ejemplos

En el ejemplo de código siguiente se usa el Type.GetFields método para obtener FieldInfo objetos para los campos de un tipo, se obtiene una RuntimeFieldHandle estructura para cada campo y, a continuación, se recuperan los FieldInfo objetos de los identificadores mediante esta sobrecarga del GetFieldFromHandle método .

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.Reflection

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
End Class

Comentarios

Los identificadores solo son válidos en el dominio de aplicación en el que se obtuvieron.

Se aplica a

GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle)

Obtiene FieldInfo para el campo representado por el identificador especificado, para el tipo genérico especificado.

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

Parámetros

handle
RuntimeFieldHandle

Estructura RuntimeFieldHandle que contiene el identificador para la representación interna de los metadatos de un campo.

declaringType
RuntimeTypeHandle

Estructura RuntimeTypeHandle que contiene el identificador para el tipo genérico que define el campo.

Devoluciones

FieldInfo

Objeto FieldInfo que representa el campo especificado por handle, en el tipo genérico especificado por declaringType.

Atributos

Excepciones

handle no es válido.

O bien declaringType no es compatible con handle. Por ejemplo, declaringType es el identificador de tipo en tiempo de ejecución de la definición de tipo genérico, y handle viene de un tipo construido.

Ejemplos

En el ejemplo siguiente se muestra cómo recuperar FieldInfo objetos para campos en clases genéricas construidas. En el ejemplo se define el tipo Test<T> genérico (Test(Of T) en Visual Basic) con un único campo denominado TestField, de tipo T. En el ejemplo se obtiene y RuntimeFieldHandle RuntimeTypeHandle para el caso en el que T es Stringy se muestra lo siguiente:

  • Se produce una excepción si se usa la sobrecarga del GetFieldFromHandle(RuntimeFieldHandle) método. Esto es true incluso si el campo no es de tipo T.

  • Se FieldInfo recupera correctamente si el identificador de tipo en tiempo de ejecución procede de la misma construcción que el identificador de campo en tiempo de ejecución, en este caso Test<string>.

  • Si el identificador de tipo en tiempo de ejecución procede de una construcción compatible, en este caso Test<object>, se recupera un FieldInfo para el campo en la construcción compatible.

  • Si el identificador de tipo en tiempo de ejecución no procede de una construcción compatible, se produce una excepción. En este caso, se especifica un tipo de valor para 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.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.

Comentarios

Los identificadores solo son válidos en el dominio de aplicación en el que se obtuvieron.

La práctica recomendada es que declaringType siempre debe ser el identificador de tipo en tiempo de ejecución del tipo construido al que handle pertenece. Es decir, si handle es un identificador de campo en tiempo de ejecución para un campo que pertenece a MyType<int> (MyType(Of Integer) en Visual Basic), declaringType es el identificador de tipo en tiempo de ejecución para MyType<int>. No use el identificador de tipo en tiempo de ejecución de la definición de tipo genérico, a menos que el identificador de campo en tiempo de ejecución represente un campo en la definición de tipo genérico.

Las implementaciones son compatibles en algunos casos. Por ejemplo, todos los tipos que se construyen a partir de una definición de tipo genérico determinada comparten una única implementación mediante tipos de referencia para los argumentos de tipo genérico. Por ejemplo, MyType<string>, MyType<object>y MyType<ArrayList> comparten la misma implementación. En esta situación, el FieldInfo objeto que se devuelve representa un campo en el tipo que declaringType especifica, independientemente del origen original de handle. Esta práctica no se recomienda, ya que solo funciona si los argumentos de tipo genérico del tipo construido son tipos de referencia.

Si un argumento genérico es un tipo de valor, el identificador de tipo en tiempo de ejecución del tipo construido no es compatible con los identificadores de campo en tiempo de ejecución de construcciones que tienen un tipo de referencia en la misma posición de parámetro genérico o que tienen un tipo de valor diferente en esa posición. En ese caso, la única manera de usar la FieldInfo.GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) sobrecarga es asegurarse de que declaringType es el identificador de tipo en tiempo de ejecución para el tipo construido al que handle pertenece.

Se aplica a