FieldInfo.GetFieldFromHandle Método

Definição

Obtém um FieldInfo para o campo representado por um handle.

Sobrecargas

Name Description
GetFieldFromHandle(RuntimeFieldHandle)

Obtém um FieldInfo para o campo representado pelo handle especificado.

GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle)

Obtém um FieldInfo para o campo representado pelo handle especificado, para o tipo genérico especificado.

GetFieldFromHandle(RuntimeFieldHandle)

Origem:
FieldInfo.CoreCLR.cs
Origem:
FieldInfo.CoreCLR.cs
Origem:
FieldInfo.CoreCLR.cs
Origem:
FieldInfo.CoreCLR.cs
Origem:
FieldInfo.CoreCLR.cs

Obtém um FieldInfo para o campo representado pelo handle 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

Uma RuntimeFieldHandle estrutura que contém o handle da representação interna dos metadados de um campo.

Devoluções

Um FieldInfo objeto que representa o corpo especificado por handle.

Exceções

handle é inválido.

Exemplos

O exemplo de código seguinte usa o Type.GetFields método para obter FieldInfo objetos para os campos de um tipo, obtém uma RuntimeFieldHandle estrutura para cada campo e depois recupera os FieldInfo objetos dos handles usando esta sobrecarga do GetFieldFromHandle método.

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

Observações

Os handles são válidos apenas no domínio de aplicação em que foram obtidos.

Aplica-se a

GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle)

Origem:
FieldInfo.CoreCLR.cs
Origem:
FieldInfo.CoreCLR.cs
Origem:
FieldInfo.CoreCLR.cs
Origem:
FieldInfo.CoreCLR.cs
Origem:
FieldInfo.CoreCLR.cs

Obtém um FieldInfo para o campo representado pelo handle especificado, para o 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

Uma RuntimeFieldHandle estrutura que contém o handle da representação interna dos metadados de um campo.

declaringType
RuntimeTypeHandle

Uma RuntimeTypeHandle estrutura que contém o handle do tipo genérico que define o campo.

Devoluções

Um objeto que FieldInfo representa o corpo especificado por handle, no tipo genérico especificado por declaringType.

Atributos

Exceções

handle é inválido.

-ou-

declaringType não é compatível com handle. Por exemplo, declaringType é o handle do tipo de execução da definição genérica do tipo, e handle provém de um tipo construído.

Exemplos

O exemplo seguinte mostra como recuperar FieldInfo objetos para campos em classes genéricas construídas. O exemplo define o tipo genérico Test<T> (Test(Of T) em Visual Basic) com um único campo chamado TestField, do tipo T. O exemplo obtém o RuntimeFieldHandle e RuntimeTypeHandle para o caso em que T é String, e demonstra o seguinte:

  • É lançada uma exceção se for usado o GetFieldFromHandle(RuntimeFieldHandle) método overload. Isto é verdade mesmo que o campo não seja do tipo T.

  • A FieldInfo é recuperado com sucesso se o handle de tipo de runtime for da mesma construção que o handle de campo de runtime, neste caso Test<string>.

  • Se o handle de tipo de runtime for de uma construção compatível, neste caso Test<object>, recupera-se um FieldInfo para o campo na construção compatível.

  • Se o handle do tipo de execução não for de uma construção compatível, é lançada uma exceção. Neste caso, é especificado um 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.

Observações

Os handles são válidos apenas no domínio de aplicação em que foram obtidos.

A prática recomendada é que declaringType seja sempre o handle de tipo de execução do tipo construído a que handle pertence. Ou seja, se handle for um handle de campo em tempo de execução para um campo que pertence a MyType<int> (MyType(Of Integer) em Visual Basic), declaringType é o tipo de handle em tempo de execução para MyType<int>. Não use o handle de tipo de runtime da definição genérica de tipo, a menos que o handle de campo de runtime represente um campo na definição genérica do tipo.

As implementações são compatíveis em alguns casos. Por exemplo, uma única implementação é partilhada por todos os tipos que são construídos a partir de uma definição de tipo genérica particular, usando tipos de referência para os argumentos do tipo genérico. Por exemplo, MyType<string>, MyType<object>, e MyType<ArrayList> todos partilham a mesma implementação. Nesta situação, o FieldInfo objeto que é devolvido representa um campo no tipo que declaringType especifica, independentemente da fonte original de handle. Esta prática não é recomendada, pois só funciona se os argumentos genéricos do tipo construído forem tipos de referência.

Se um argumento genérico for um tipo de valor, o handle de tipo em tempo de execução do tipo construído não é compatível com handles de campo em tempo de execução de construções que tenham um tipo de referência na mesma posição genérica, ou que tenham um tipo de valor diferente nessa posição. Nesse caso, a única forma de usar a FieldInfo.GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) sobrecarga é garantir que declaringType é o handle do tipo de execução para o tipo construído a que handle pertence.

Aplica-se a