Udostępnij przez


TypeBuilder.GetField Metoda

Definicja

Zwraca pole zdefiniowane przez bieżący TypeBuilderelement .

Przeciążenia

GetField(Type, FieldInfo)

Zwraca pole określonego skonstruowanego typu ogólnego, które odpowiada określonemu polu definicji typu ogólnego.

GetField(String, BindingFlags)

Zwraca pole określone przez daną nazwę.

GetField(Type, FieldInfo)

Źródło:
TypeBuilder.cs
Źródło:
RuntimeTypeBuilder.cs
Źródło:
TypeBuilder.cs

Zwraca pole określonego skonstruowanego typu ogólnego, które odpowiada określonemu polu definicji typu ogólnego.

public:
 static System::Reflection::FieldInfo ^ GetField(Type ^ type, System::Reflection::FieldInfo ^ field);
public static System.Reflection.FieldInfo GetField (Type type, System.Reflection.FieldInfo field);
static member GetField : Type * System.Reflection.FieldInfo -> System.Reflection.FieldInfo
Public Shared Function GetField (type As Type, field As FieldInfo) As FieldInfo

Parametry

type
Type

Skonstruowany typ ogólny, którego pole jest zwracane.

field
FieldInfo

Pole w ogólnej definicji typu , typektóre określa, które pole ma type być zwracane.

Zwraca

FieldInfo Obiekt reprezentujący pole type odpowiadające fieldelementowi , który określa pole należące do ogólnej definicji typetypu .

Wyjątki

type nie reprezentuje typu ogólnego.

-lub-

type nie jest typu TypeBuilder.

-lub-

Deklarowany typ field nie jest definicją typu ogólnego.

-lub-

Deklarowany typ field nie jest ogólną definicją typetypu .

Przykłady

Poniższy przykład kodu zawiera kod źródłowy dla klasy ogólnej o nazwie Sample, która ma parametr typu o nazwie T. Klasa ma pole o nazwie Field, typu i metodę ogólną o nazwie GM z własnym parametrem typu To nazwie U. Metoda GM tworzy wystąpienie klasy Sample, podstawiając własny parametr U typu parametru typu parametru Sample, i przechowuje jego parametr wejściowy w pliku Field. Ten kod źródłowy jest kompilowany, ale nie jest używany; Można go wyświetlić za pomocą Ildasm.exe (IL Dezasembler) i porównać go z kodem emitowany przez klasę Example.

Kod w klasie Example pokazuje użycie GetField metody do emitowania kodu ogólnego. Metoda Main klasy Example tworzy zestaw dynamiczny zawierający klasę o nazwie Sample, i używa DefineGenericParameters metody , aby ją ogólną, dodając parametr typu o nazwie T. Konstruktor bez parametrów i pole o nazwie Field, typu T, są dodawane do klasy Sample. Metoda GM jest dodawana i przekształcana w metodę ogólną przy użyciu MethodBuilder.DefineGenericParameters metody . Parametr GM typu ma nazwę U. Po zdefiniowaniu parametru typu podpis GM jest dodawany przy użyciu MethodBuilder.SetSignature metody . Nie ma zwracanego typu i nie ma wymaganych ani niestandardowych modyfikatorów, więc wszystkie parametry tej metody są null z wyjątkiem parameterTypes; parameterTypes ustawia typ jedynego parametru metody na U, parametr typu ogólnego metody. Treść metody tworzy wystąpienie skonstruowanego typu Sample<U> (Sample(Of U) w Visual Basic), przypisuje parametr metody do Fieldmetody , a następnie wyświetla wartość .Field Metoda GetField służy do utworzenia obiektu FieldInfo reprezentującego pole skonstruowanego typu Sample<U> ogólnego w OpCodes.Stfld instrukcjach i OpCodes.Ldfld .

Typ fikcyjny jest definiowany do przechowywania metody Mainpunktu wejścia . W treści metody statycznej GM jest wywoływana na skonstruowanym typie ogólnym (Sample(Of Integer) w Visual Basic), z typem Sample<int>String zastąpionym przez U.Main

Po uruchomieniu przykładu kodu program zapisuje emitowany zestaw jako TypeBuilderGetFieldExample.exe. Możesz uruchomić TypeBuilderGetFieldExample.exe i użyć Ildasm.exe (IL Dezasembler), aby porównać emitowany kod z kodem dla Sample klasy skompilowanej w samym przykładzie kodu.

using System;
using System.Reflection;
using System.Reflection.Emit;

// Compare the MSIL in this class to the MSIL
// generated by the Reflection.Emit code in class
// Example.
public class Sample<T>
{
  public T Field;
  public static void GM<U>(U val)
  {
    Sample<U> s = new Sample<U>();
    s.Field = val;
    Console.WriteLine(s.Field);
  }
}

public class Example
{
    public static void Main()
    {
        AppDomain myDomain = AppDomain.CurrentDomain;
        AssemblyName myAsmName =
            new AssemblyName("TypeBuilderGetFieldExample");
        AssemblyBuilder myAssembly = myDomain.DefineDynamicAssembly(
            myAsmName, AssemblyBuilderAccess.Save);
        ModuleBuilder myModule = myAssembly.DefineDynamicModule(
            myAsmName.Name,
            myAsmName.Name + ".exe");

        // Define the sample type.
        TypeBuilder myType = myModule.DefineType("Sample",
            TypeAttributes.Class | TypeAttributes.Public);

        // Add a type parameter, making the type generic.
        string[] typeParamNames = {"T"};
        GenericTypeParameterBuilder[] typeParams =
            myType.DefineGenericParameters(typeParamNames);

        // Define a default constructor. Normally it would
        // not be necessary to define the default constructor,
        // but in this case it is needed for the call to
        // TypeBuilder.GetConstructor, which gets the default
        // constructor for the generic type constructed from
        // Sample<T>, in the generic method GM<U>.
        ConstructorBuilder ctor = myType.DefineDefaultConstructor(
            MethodAttributes.PrivateScope | MethodAttributes.Public |
            MethodAttributes.HideBySig | MethodAttributes.SpecialName |
            MethodAttributes.RTSpecialName);

        // Add a field of type T, with the name Field.
        FieldBuilder myField = myType.DefineField("Field",
            typeParams[0],
            FieldAttributes.Public);

        // Add a method and make it generic, with a type
        // parameter named U. Note how similar this is to
        // the way Sample is turned into a generic type. The
        // method has no signature, because the type of its
        // only parameter is U, which is not yet defined.
        MethodBuilder genMethod = myType.DefineMethod("GM",
            MethodAttributes.Public | MethodAttributes.Static);
        string[] methodParamNames = {"U"};
        GenericTypeParameterBuilder[] methodParams =
            genMethod.DefineGenericParameters(methodParamNames);

        // Now add a signature for genMethod, specifying U
        // as the type of the parameter. There is no return value
        // and no custom modifiers.
        genMethod.SetSignature(null, null, null,
            new Type[] { methodParams[0] }, null, null);

        // Emit a method body for the generic method.
        ILGenerator ilg = genMethod.GetILGenerator();
        // Construct the type Sample<U> using MakeGenericType.
        Type SampleOfU = myType.MakeGenericType( methodParams[0] );
        // Create a local variable to store the instance of
        // Sample<U>.
        ilg.DeclareLocal(SampleOfU);
        // Call the default constructor. Note that it is
        // necessary to have the default constructor for the
        // constructed generic type Sample<U>; use the
        // TypeBuilder.GetConstructor method to obtain this
        // constructor.
        ConstructorInfo ctorOfU = TypeBuilder.GetConstructor(
            SampleOfU, ctor);
        ilg.Emit(OpCodes.Newobj, ctorOfU);
        // Store the instance in the local variable; load it
        // again, and load the parameter of genMethod.
        ilg.Emit(OpCodes.Stloc_0);
        ilg.Emit(OpCodes.Ldloc_0);
        ilg.Emit(OpCodes.Ldarg_0);
        // In order to store the value in the field of the
        // instance of Sample<U>, it is necessary to have
        // a FieldInfo representing the field of the
        // constructed type. Use TypeBuilder.GetField to
        // obtain this FieldInfo.
        FieldInfo FieldOfU = TypeBuilder.GetField(
            SampleOfU, myField);
        // Store the value in the field.
        ilg.Emit(OpCodes.Stfld, FieldOfU);
        // Load the instance, load the field value, box it
        // (specifying the type of the type parameter, U), and
        // print it.
        ilg.Emit(OpCodes.Ldloc_0);
        ilg.Emit(OpCodes.Ldfld, FieldOfU);
        ilg.Emit(OpCodes.Box, methodParams[0]);
        MethodInfo writeLineObj =
            typeof(Console).GetMethod("WriteLine",
                new Type[] { typeof(object) });
        ilg.EmitCall(OpCodes.Call, writeLineObj, null);
        ilg.Emit(OpCodes.Ret);

        // Emit an entry point method; this must be in a
        // non-generic type.
        TypeBuilder dummy = myModule.DefineType("Dummy",
            TypeAttributes.Class | TypeAttributes.NotPublic);
        MethodBuilder entryPoint = dummy.DefineMethod("Main",
            MethodAttributes.Public | MethodAttributes.Static,
            null, null);
        ilg = entryPoint.GetILGenerator();
        // In order to call the static generic method GM, it is
        // necessary to create a constructed type from the
        // generic type definition for Sample. This can be any
        // constructed type; in this case Sample<int> is used.
        Type SampleOfInt =
            myType.MakeGenericType( typeof(int) );
        // Next get a MethodInfo representing the static generic
        // method GM on type Sample<int>.
        MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt,
            genMethod);
        // Next get a MethodInfo for GM<string>, which is the
        // instantiation of GM that Main calls.
        MethodInfo GMOfString =
            SampleOfIntGM.MakeGenericMethod( typeof(string) );
        // Finally, emit the call. Push a string onto
        // the stack, as the argument for the generic method.
        ilg.Emit(OpCodes.Ldstr, "Hello, world!");
        ilg.EmitCall(OpCodes.Call, GMOfString, null);
        ilg.Emit(OpCodes.Ret);

        myType.CreateType();
        dummy.CreateType();
        myAssembly.SetEntryPoint(entryPoint);
        myAssembly.Save(myAsmName.Name + ".exe");

        Console.WriteLine(myAsmName.Name + ".exe has been saved.");
    }
}
Imports System.Reflection
Imports System.Reflection.Emit

' Compare the MSIL in this class to the MSIL
' generated by the Reflection.Emit code in class
' Example.
Public Class Sample(Of T)
    Public Field As T
    Public Shared Sub GM(Of U)(ByVal val As U)
        Dim s As New Sample(Of U)
        s.Field = val
        Console.WriteLine(s.Field)
    
    End Sub
End Class 

Public Class Example
    
    Public Shared Sub Main() 
        Dim myDomain As AppDomain = AppDomain.CurrentDomain
        Dim myAsmName As New AssemblyName("TypeBuilderGetFieldExample")
        Dim myAssembly As AssemblyBuilder = _
            myDomain.DefineDynamicAssembly(myAsmName, _
                AssemblyBuilderAccess.Save)
        Dim myModule As ModuleBuilder = _
            myAssembly.DefineDynamicModule(myAsmName.Name, _
                myAsmName.Name & ".exe")
        
        ' Define the sample type.
        Dim myType As TypeBuilder = myModule.DefineType( _
            "Sample", _
            TypeAttributes.Class Or TypeAttributes.Public)
        
        ' Add a type parameter, making the type generic.
        Dim typeParamNames() As String = { "T" }
        Dim typeParams As GenericTypeParameterBuilder() = _
            myType.DefineGenericParameters(typeParamNames)
        
        ' Define a default constructor. Normally it would 
        ' not be necessary to define the default constructor,
        ' but in this case it is needed for the call to
        ' TypeBuilder.GetConstructor, which gets the default
        ' constructor for the generic type constructed from 
        ' Sample(Of T), in the generic method GM(Of U).
        Dim ctor As ConstructorBuilder = _
            myType.DefineDefaultConstructor( _
                MethodAttributes.PrivateScope Or MethodAttributes.Public _
                Or MethodAttributes.HideBySig Or MethodAttributes.SpecialName _
                Or MethodAttributes.RTSpecialName)
        
        ' Add a field of type T, with the name Field.
        Dim myField As FieldBuilder = myType.DefineField( _
            "Field", typeParams(0), FieldAttributes.Public)
        
        ' Add a method and make it generic, with a type 
        ' parameter named U. Note how similar this is to 
        ' the way Sample is turned into a generic type. The
        ' method has no signature, because the type of its
        ' only parameter is U, which is not yet defined.
        Dim genMethod As MethodBuilder = _
            myType.DefineMethod("GM", _
                MethodAttributes.Public Or MethodAttributes.Static)
        Dim methodParamNames() As String = { "U" }
        Dim methodParams As GenericTypeParameterBuilder() = _
            genMethod.DefineGenericParameters(methodParamNames)

        ' Now add a signature for genMethod, specifying U
        ' as the type of the parameter. There is no return value
        ' and no custom modifiers.
        genMethod.SetSignature(Nothing, Nothing, Nothing, _
            New Type() { methodParams(0) }, Nothing, Nothing)
        
        ' Emit a method body for the generic method.
        Dim ilg As ILGenerator = genMethod.GetILGenerator()
        ' Construct the type Sample(Of U) using MakeGenericType.
        Dim SampleOfU As Type = _
            myType.MakeGenericType(methodParams(0))
        ' Create a local variable to store the instance of
        ' Sample(Of U).
        ilg.DeclareLocal(SampleOfU)
        ' Call the default constructor. Note that it is 
        ' necessary to have the default constructor for the
        ' constructed generic type Sample(Of U); use the 
        ' TypeBuilder.GetConstructor method to obtain this 
        ' constructor.
        Dim ctorOfU As ConstructorInfo = _
            TypeBuilder.GetConstructor(SampleOfU, ctor)
        ilg.Emit(OpCodes.Newobj, ctorOfU)
        ' Store the instance in the local variable; load it
        ' again, and load the parameter of genMethod.
        ilg.Emit(OpCodes.Stloc_0)
        ilg.Emit(OpCodes.Ldloc_0)
        ilg.Emit(OpCodes.Ldarg_0)
        ' In order to store the value in the field of the
        ' instance of Sample(Of U), it is necessary to have 
        ' a FieldInfo representing the field of the 
        ' constructed type. Use TypeBuilder.GetField to 
        ' obtain this FieldInfo.
        Dim FieldOfU As FieldInfo = _
            TypeBuilder.GetField(SampleOfU, myField)
        ' Store the value in the field. 
        ilg.Emit(OpCodes.Stfld, FieldOfU)
        ' Load the instance, load the field value, box it
        ' (specifying the type of the type parameter, U), 
        ' and print it.
        ilg.Emit(OpCodes.Ldloc_0)
        ilg.Emit(OpCodes.Ldfld, FieldOfU)
        ilg.Emit(OpCodes.Box, methodParams(0))
        Dim writeLineObj As MethodInfo = _
            GetType(Console).GetMethod("WriteLine", _
                New Type() {GetType(Object)})
        ilg.EmitCall(OpCodes.Call, writeLineObj, Nothing)
        ilg.Emit(OpCodes.Ret)
        
        ' Emit an entry point method; this must be in a
        ' non-generic type.
        Dim dummy As TypeBuilder = _
            myModule.DefineType("Dummy", _
                TypeAttributes.Class Or TypeAttributes.NotPublic)
        Dim entryPoint As MethodBuilder = _
            dummy.DefineMethod("Main", _
                MethodAttributes.Public Or MethodAttributes.Static, _
                Nothing, Nothing)
        ilg = entryPoint.GetILGenerator()
        ' In order to call the static generic method GM, it is
        ' necessary to create a constructed type from the 
        ' generic type definition for Sample. This can be ANY
        ' constructed type; in this case Sample(Of Integer)
        ' is used.
        Dim SampleOfInt As Type = _
            myType.MakeGenericType(GetType(Integer))
        ' Next get a MethodInfo representing the static generic
        ' method GM on type Sample(Of Integer).
        Dim SampleOfIntGM As MethodInfo = _
            TypeBuilder.GetMethod(SampleOfInt, genMethod)
        ' Next get a MethodInfo for GM(Of String), which is the 
        ' instantiation of generic method GM that is called
        ' by Sub Main.
        Dim GMOfString As MethodInfo = _
            SampleOfIntGM.MakeGenericMethod(GetType(String))
        ' Finally, emit the call. Push a string onto
        ' the stack, as the argument for the generic method.
        ilg.Emit(OpCodes.Ldstr, "Hello, world!")
        ilg.EmitCall(OpCodes.Call, GMOfString, Nothing)
        ilg.Emit(OpCodes.Ret)
        
        myType.CreateType()
        dummy.CreateType()
        myAssembly.SetEntryPoint(entryPoint)
        myAssembly.Save(myAsmName.Name & ".exe")
        
        Console.WriteLine(myAsmName.Name & ".exe has been saved.")
    
    End Sub 
End Class

Uwagi

Metoda GetField umożliwia uzyskanie FieldInfo obiektu, który reprezentuje pole skonstruowanego typu ogólnego, którego definicja typu ogólnego jest reprezentowana przez TypeBuilder obiekt.

Załóżmy na przykład, że masz TypeBuilder obiekt reprezentujący typ G<T> składni języka C# (w języku Visual Basic generic <T> ref class G w języku C++) i FieldBuilder obiekt reprezentujący pole public T F w składni języka C# (G(Of T)Public F As Tw języku Visual Basic public: T F w języku C++), który jest definiowany przez G<T>program . Załóżmy, że G<T> ma metodę ogólną z parametrem U typu, który tworzy wystąpienie skonstruowanego typu G<U> i wywołuje pole F w tym wystąpieniu. Aby emitować wywołanie funkcji, potrzebny jest FieldInfo obiekt reprezentujący F typ skonstruowany — innymi słowy, jest to typ U zamiast typu T. W tym celu najpierw wywołaj metodę MakeGenericType w TypeBuilder obiekcie, określając GenericTypeParameterBuilder obiekt, który reprezentuje U jako argument typu. Następnie wywołaj metodę GetField przy użyciu wartości zwracanej MakeGenericType metody jako parametru type i FieldBuilder obiektu, który reprezentuje F jako parametr field. Zwracana FieldInfo wartość to obiekt, który należy emitować wywołanie funkcji. W przykładzie kodu pokazano ten scenariusz.

Dotyczy

GetField(String, BindingFlags)

Źródło:
TypeBuilder.cs

Zwraca pole określone przez daną nazwę.

public:
 override System::Reflection::FieldInfo ^ GetField(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
public override System.Reflection.FieldInfo? GetField (string name, System.Reflection.BindingFlags bindingAttr);
public override System.Reflection.FieldInfo GetField (string name, System.Reflection.BindingFlags bindingAttr);
override this.GetField : string * System.Reflection.BindingFlags -> System.Reflection.FieldInfo
Public Overrides Function GetField (name As String, bindingAttr As BindingFlags) As FieldInfo

Parametry

name
String

Nazwa pola do pobrania.

bindingAttr
BindingFlags

Musi to być nieco flaga z BindingFlags jak w InvokeMethod, NonPublici tak dalej.

Zwraca

FieldInfo Zwraca obiekt reprezentujący pole zadeklarowane lub dziedziczone przez ten typ z określoną nazwą i modyfikatorem publicznym lub innym niż publiczny. Jeśli nie ma dopasowań, null zostanie zwrócona.

Wyjątki

Ta metoda nie jest implementowana dla niekompletnych typów.

Uwagi

Pobierz typ przy użyciu metody Type.GetType lub Assembly.GetType i użyj odbicia dla pobranego typu.

Dotyczy