Share via


TypeBuilder.GetField Yöntem

Tanım

Geçerli TypeBuildertarafından tanımlanan bir alan döndürür.

Aşırı Yüklemeler

GetField(Type, FieldInfo)

Belirtilen oluşturulan genel türün, genel tür tanımının belirtilen alanına karşılık gelen alanını döndürür.

GetField(String, BindingFlags)

Verilen adla belirtilen alanı döndürür.

GetField(Type, FieldInfo)

Kaynak:
TypeBuilder.cs
Kaynak:
RuntimeTypeBuilder.cs
Kaynak:
TypeBuilder.cs

Belirtilen oluşturulan genel türün, genel tür tanımının belirtilen alanına karşılık gelen alanını döndürür.

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

Parametreler

type
Type

Alanı döndürülen oluşturulan genel tür.

field
FieldInfo

genel tür tanımında type, döndürülecek alanı belirten bir alan type .

Döndürülenler

FieldInfo genel tür tanımına fieldtypeait bir alanı belirten öğesine karşılık gelen alanını type temsil eden nesne.

Özel durumlar

type genel bir türü temsil etmez.

-veya-

type türünde TypeBuilderdeğil.

-veya-

Bildirim türü field genel bir tür tanımı değil.

-veya-

bildirim türü field , genel tür tanımı typedeğildir.

Örnekler

Aşağıdaki kod örneği, adlı Ttür parametresine sahip Sample adlı genel bir sınıfın kaynak kodunu içerir. sınıfı, türünde Tadlı Fieldbir alana ve adlı kendi tür parametresine sahip adlı GM genel bir yönteme Usahiptir. YöntemiGM, türü parametresi için kendi tür parametresini U değiştirerek öğesinin Samplebir örneğini Sampleoluşturur ve giriş parametresini içinde Fielddepolar. Bu kaynak kod derlenmiş ancak kullanılmaz; Ildasm.exe (IL Disassembler) ile görüntüleyebilir ve sınıfı Exampletarafından yayılan kodla karşılaştırabilirsiniz.

sınıfındaki Example kod, genel kod yaymak için yönteminin GetField kullanımını gösterir. Main sınıfının Example yöntemi adlı Samplebir sınıf içeren dinamik bir derleme oluşturur ve adlı bir tür parametresi Tekleyerek bunu genel hale getirmek için yöntemini kullanırDefineGenericParameters. parametresiz oluşturucu ve türünde Tadlı Fieldbir alan sınıfına Sampleeklenir. Yöntemi kullanılarak bir yöntem GM eklenir ve genel bir yönteme MethodBuilder.DefineGenericParameters dönüştürülür. türü parametresi GM olarak adlandırılır U. tür parametresi tanımlandıktan sonra, yöntemi kullanılarak MethodBuilder.SetSignature imzası GM eklenir. Dönüş türü yoktur ve gerekli veya özel değiştirici yoktur, bu nedenle bu yöntemin tüm parametreleri dışındadır nullparameterTypes; parameterTypes yöntemin tek parametresinin türünü yönteminin genel tür parametresi olarak Uayarlar. yönteminin gövdesi, oluşturulan türün Sample<U> (Sample(Of U) Visual Basic'te) bir örneğini oluşturur, yönteminin parametresini öğesine Fieldatar ve değerini yazdırır Field. GetField yöntemi, ve OpCodes.Ldfld yönergelerinde oluşturulan genel türün Sample<U>OpCodes.Stfld alanını temsil eden bir FieldInfo oluşturmak için kullanılır.

Giriş noktası yöntemini Maintutmak için bir kukla türü tanımlanır. gövdesinde Mainstatik GM yöntem, türü ile değiştirildiğinde, yapılandırılmış genel tür Sample<int> üzerinde (Sample(Of Integer) Visual Basic'te) String çağrılır U.

Kod örneği çalıştırıldığında, yayılan derlemeyi TypeBuilderGetFieldExample.exe olarak kaydeder. TypeBuilderGetFieldExample.exe çalıştırabilir ve Ildasm.exe (IL Disassembler) kullanarak, yayılan kodu kod örneğinin kendisinde derlenen sınıfın Sample koduyla karşılaştırabilirsiniz.

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

Açıklamalar

yöntemi, GetField genel tür tanımı bir FieldInfo nesneyle temsil edilen, oluşturulan bir genel türün alanını temsil eden bir nesne almak için bir TypeBuilder yol sağlar.

Örneğin, C# söz dizimindeki (G(Of T)Visual Basic'te, generic <T> ref class G C++'da) türü G<T> temsil eden bir nesneniz ve C# söz diziminde (Public F As TVisual Basic'te, public: T F C++'da) tarafından G<T>tanımlanan bir alanı public T F temsil eden bir FieldBuilder nesneniz TypeBuilder olduğunu varsayalım. Bunun, oluşturulan türün G<T> bir örneğini oluşturan ve bu örnekte alanı F çağıran tür G<U> parametresine U sahip genel bir yöntemi olduğunu varsayalım. İşlev çağrısını yaymak için, oluşturduğunuz türü temsil eden bir nesneye ihtiyacınız vardır; başka bir FieldInfo deyişle, türü yerine türündedir UT.F Bunu yapmak için, önce nesnede TypeBuilder yöntemini çağırın MakeGenericTypeGenericTypeParameterBuilder ve tür bağımsız değişkeni olarak temsil U eden nesneyi belirtin. Ardından yönteminin GetField dönüş değeriyle MakeGenericType parametresini ve FieldBuilder parametresini typefieldtemsil F eden nesnesini çağırın. Dönüş değeri, işlev çağrısını FieldInfo yaymak için ihtiyacınız olan nesnedir. Kod örneği bu senaryoyu gösterir.

Şunlara uygulanır

GetField(String, BindingFlags)

Kaynak:
TypeBuilder.cs

Verilen adla belirtilen alanı döndürür.

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

Parametreler

name
String

Alınacak alanın adı.

bindingAttr
BindingFlags

Bu, , NonPublicve benzeri gibi InvokeMethodbir bit bayrağı BindingFlags olmalıdır.

Döndürülenler

FieldInfo Belirtilen ad ve ortak veya genel olmayan değiştirici ile bu tür tarafından bildirilen veya devralınan alanı temsil eden nesneyi döndürür. Eşleşme null yoksa döndürülür.

Özel durumlar

Bu yöntem tamamlanmamış türler için uygulanmaz.

Açıklamalar

veya Assembly.GetType kullanarak Type.GetType türü alın ve alınan türdeki yansımayı kullanın.

Şunlara uygulanır