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

Definizione

Ottiene un oggetto FieldInfo per il campo rappresentato da un handle.Gets a FieldInfo for the field represented by a handle.

Overload

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

Ottiene un oggetto FieldInfo per il campo rappresentato dall'handle specificato.Gets a FieldInfo for the field represented by the specified handle.

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

Ottiene un oggetto FieldInfo per il campo rappresentato dall'handle specificato, per il tipo generico specificato.Gets a FieldInfo for the field represented by the specified handle, for the specified generic type.

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

Ottiene un oggetto FieldInfo per il campo rappresentato dall'handle specificato.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

Parametri

handle
RuntimeFieldHandle RuntimeFieldHandle RuntimeFieldHandle RuntimeFieldHandle

Struttura RuntimeFieldHandle contenente l'handle per la rappresentazione dei metadati interni di un campo.A RuntimeFieldHandle structure that contains the handle to the internal metadata representation of a field.

Restituisce

Oggetto FieldInfo che rappresenta il campo specificato da handle.A FieldInfo object representing the field specified by handle.

Eccezioni

Esempi

Nell'esempio di codice seguente viene Type.GetFields usato il metodo FieldInfo per ottenere gli oggetti per i campi di un tipo RuntimeFieldHandle , viene ottenuta una struttura FieldInfo per ogni campo e quindi vengono recuperati gli oggetti dagli handle usando questo overload del GetFieldFromHandlecomandometodo.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.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 'FieldInfo_GetFieldFromHandle

Commenti

Gli handle sono validi solo nel dominio dell'applicazione in cui sono stati ottenuti.Handles are valid only in the application domain in which they were obtained.

Sicurezza

ReflectionPermission
Quando viene richiamato ad associazione tardiva tramite InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])meccanismi come.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumerazione associata: MemberAccess.Associated enumeration: MemberAccess.

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

Ottiene un oggetto FieldInfo per il campo rappresentato dall'handle specificato, per il tipo generico specificato.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

Parametri

handle
RuntimeFieldHandle RuntimeFieldHandle RuntimeFieldHandle RuntimeFieldHandle

Struttura RuntimeFieldHandle contenente l'handle per la rappresentazione dei metadati interni di un campo.A RuntimeFieldHandle structure that contains the handle to the internal metadata representation of a field.

declaringType
RuntimeTypeHandle RuntimeTypeHandle RuntimeTypeHandle RuntimeTypeHandle

Struttura RuntimeTypeHandle contenente l'handle al tipo generico che definisce il campo.A RuntimeTypeHandle structure that contains the handle to the generic type that defines the field.

Restituisce

Oggetto FieldInfo che rappresenta il campo specificato da handle, nel tipo generico specificato da declaringType.A FieldInfo object representing the field specified by handle, in the generic type specified by declaringType.

Eccezioni

handle non è valido.handle is invalid.

-oppure--or- declaringType non è compatibile con handle.declaringType is not compatible with handle. Ad esempio, il parametro declaringType è l'handle di tipo runtime della definizione di tipo generico e handle proviene da un tipo costruito.For example, declaringType is the runtime type handle of the generic type definition, and handle comes from a constructed type.

Esempi

Nell'esempio seguente viene illustrato come recuperare FieldInfo oggetti per campi in classi generiche costruite.The following example shows how to retrieve FieldInfo objects for fields on constructed generic classes. Nell'esempio viene definito il tipo Test<T> genericoTest(Of T) (in Visual Basic) con un singolo campo TestFielddenominato, di Ttipo.The example defines the generic type Test<T> (Test(Of T) in Visual Basic) with a single field named TestField, of type T. Nell'esempio vengono ottenuti RuntimeTypeHandle gli RuntimeFieldHandle elementi e per T il Stringcaso in cui è e viene illustrato quanto segue:The example gets the RuntimeFieldHandle and RuntimeTypeHandle for the case where T is String, and demonstrates the following:

  • Se viene utilizzato l'overload del GetFieldFromHandle(RuntimeFieldHandle) metodo, viene generata un'eccezione.An exception is thrown if the GetFieldFromHandle(RuntimeFieldHandle) method overload is used. Questo vale anche se il campo non è di tipo T.This is true even if the field is not of type T.

  • Un FieldInfo viene recuperato correttamente se l'handle del tipo di runtime è dalla stessa costruzione dell'handle del campo Runtime, in questo Test<string>caso.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>.

  • Se l'handle del tipo di runtime è da una costruzione compatibile, in Test<object>questo caso FieldInfo viene recuperato un oggetto per il campo nella costruzione compatibile.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.

  • Se l'handle del tipo di runtime non è una costruzione compatibile, viene generata un'eccezione.If the runtime type handle is not from a compatible construction, an exception is thrown. In questo caso, viene specificato un tipo di valore Tper.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.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.Handles are valid only in the application domain in which they were obtained.

La procedura consigliata è declaringType che deve essere sempre l'handle del tipo di runtime del tipo handle costruito a cui appartiene.The recommended practice is that declaringType should always be the runtime type handle of the constructed type that handle belongs to. Ovvero handle , se è un handle di campo di runtime per un campo che appartiene MyType<int> aMyType(Of Integer) (in Visual Basic) declaringType , è l'handle del tipo MyType<int>di runtime per.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>. Non usare l'handle del tipo di runtime della definizione di tipo generico, a meno che l'handle del campo Runtime non rappresenti un campo nella definizione di tipo generico.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.

In alcuni casi le implementazioni sono compatibili.Implementations are compatible in some cases. Una singola implementazione, ad esempio, viene condivisa da tutti i tipi costruiti da una definizione di tipo generico specifica utilizzando i tipi riferimento per gli argomenti di tipo generico.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. Ad esempio MyType<string> MyType<object>,, e MyType<ArrayList> condividono la stessa implementazione.For example, MyType<string>, MyType<object>, and MyType<ArrayList> all share the same implementation. In questa situazione, l' FieldInfo oggetto restituito rappresenta un campo nel tipo che declaringType specifica, indipendentemente dall'origine originale di handle.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. Questa pratica non è consigliata, perché funziona solo se gli argomenti di tipo generico del tipo costruito sono tipi di riferimento.This practice is not recommended, because it works only if the generic type arguments of the constructed type are reference types.

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 con un tipo di valore diverso in tale posizione .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. In tal caso, l'unico modo per usare l' FieldInfo.GetFieldFromHandle(RuntimeFieldHandle, RuntimeTypeHandle) overload è garantire che declaringType sia l'handle del tipo di runtime per il tipo costruito handle a cui appartiene.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.

Sicurezza

ReflectionPermission
Quando viene richiamato ad associazione tardiva tramite InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])meccanismi come.when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Enumerazione associata: MemberAccess.Associated enumeration: MemberAccess.

Si applica a