FieldInfo.GetFieldFromHandle Metodo

Definizione

Ottiene un oggetto FieldInfo per il campo rappresentato da un handle.

Overload

GetFieldFromHandle(RuntimeFieldHandle)

Ottiene un oggetto FieldInfo per il campo rappresentato dall'handle specificato.

GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle)

Ottiene un oggetto FieldInfo per il campo rappresentato dall'handle specificato, per il tipo generico specificato.

GetFieldFromHandle(RuntimeFieldHandle)

Source:
FieldInfo.CoreCLR.cs
Source:
FieldInfo.CoreCLR.cs
Source:
FieldInfo.CoreCLR.cs

Ottiene un oggetto FieldInfo per il campo rappresentato dall'handle specificato.

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

Parametri

handle
RuntimeFieldHandle

Struttura RuntimeFieldHandle contenente l'handle per la rappresentazione dei metadati interni di un campo.

Restituisce

Oggetto FieldInfo che rappresenta il campo specificato da handle.

Eccezioni

handle non è valido.

Esempio

Nell'esempio di codice seguente viene usato il Type.GetFields metodo per ottenere FieldInfo oggetti per i campi di un tipo, ottiene una RuntimeFieldHandle struttura per ogni campo e quindi recupera gli FieldInfo oggetti dagli handle usando questo overload del GetFieldFromHandle metodo.

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

Commenti

Gli handle sono validi solo nel dominio dell'applicazione in cui sono stati ottenuti.

Si applica a

GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle)

Source:
FieldInfo.CoreCLR.cs
Source:
FieldInfo.CoreCLR.cs
Source:
FieldInfo.CoreCLR.cs

Ottiene un oggetto FieldInfo per il campo rappresentato dall'handle specificato, per il tipo generico specificato.

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

Parametri

handle
RuntimeFieldHandle

Struttura RuntimeFieldHandle contenente l'handle per la rappresentazione dei metadati interni di un campo.

declaringType
RuntimeTypeHandle

Struttura RuntimeTypeHandle contenente l'handle al tipo generico che definisce il campo.

Restituisce

Oggetto FieldInfo che rappresenta il campo specificato da handle, nel tipo generico specificato da declaringType.

Attributi

Eccezioni

handle non è valido.

-oppure-

declaringType non è compatibile con handle. Ad esempio, il parametro declaringType è l'handle di tipo runtime della definizione di tipo generico e handle proviene da un tipo costruito.

Esempio

Nell'esempio seguente viene illustrato come recuperare FieldInfo oggetti per i campi in classi generiche costruite. L'esempio definisce il tipo Test<T> generico (Test(Of T) in Visual Basic) con un singolo campo denominato TestField, di tipo T. L'esempio ottiene e RuntimeFieldHandleRuntimeTypeHandle per il caso in cui T è String, e illustra quanto segue:

  • Viene generata un'eccezione se viene usato l'overload del GetFieldFromHandle(RuntimeFieldHandle) metodo. Questo valore è vero anche se il campo non è di tipo T.

  • Viene FieldInfo recuperato correttamente se l'handle del tipo di runtime proviene dalla stessa costruzione dell'handle del campo di runtime, in questo caso Test<string>.

  • Se l'handle del tipo di runtime proviene da una costruzione compatibile, in questo caso Test<object>, viene recuperato un FieldInfo oggetto per il campo sulla costruzione compatibile.

  • Se l'handle del tipo di runtime non proviene da una costruzione compatibile, viene generata un'eccezione. In questo caso, viene specificato un tipo di valore per 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.

Commenti

Gli handle sono validi solo nel dominio dell'applicazione in cui sono stati ottenuti.

La procedura consigliata è che declaringType deve essere sempre l'handle del tipo di runtime del tipo costruito a cui handle appartiene. Ovvero, se handle è un handle di campo di runtime per un campo che appartiene a MyType<int> (MyType(Of Integer) in Visual Basic), declaringType è l'handle del tipo di runtime per MyType<int>. Non usare l'handle del tipo di runtime della definizione di tipo generico, a meno che l'handle del campo di runtime non rappresenti un campo nella definizione del tipo generico.

Le implementazioni sono compatibili in alcuni casi. Ad esempio, una singola implementazione viene condivisa da tutti i tipi creati da una determinata definizione di tipo generico usando i tipi di riferimento per gli argomenti di tipo generico. Ad esempio, MyType<string>, MyType<object>e MyType<ArrayList> tutte condividono la stessa implementazione. In questa situazione, l'oggetto FieldInfo restituito rappresenta un campo sul tipo che declaringType specifica, indipendentemente dall'origine originale di handle. Questa procedura non è consigliata perché funziona solo se gli argomenti di tipo generico del tipo costruito sono tipi di riferimento.

Se un argomento generico è un tipo di valore, l'handle del tipo di runtime del tipo costruito non è compatibile con gli handle dei campi di runtime dalle costruzioni che hanno un tipo di riferimento nella stessa posizione del parametro generico o che hanno un tipo di valore diverso in tale posizione. In questo caso, l'unico modo per usare l'overload consiste nel garantire che declaringType sia l'handle FieldInfo.GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) del tipo di runtime per il tipo costruito a handle cui appartiene.

Si applica a