TypeBuilder.GetField TypeBuilder.GetField TypeBuilder.GetField TypeBuilder.GetField Method

定義

現在の TypeBuilder で定義されているフィールドを返します。Returns a field defined by the current TypeBuilder.

オーバーロード

GetField(String, BindingFlags) GetField(String, BindingFlags) GetField(String, BindingFlags) GetField(String, BindingFlags)

指定した名前で指定されたフィールドを返します。Returns the field specified by the given name.

GetField(Type, FieldInfo) GetField(Type, FieldInfo) GetField(Type, FieldInfo)

ジェネリック型定義の指定されたフィールドに対応する、指定の構築されたジェネリック型のフィールドを返します。Returns the field of the specified constructed generic type that corresponds to the specified field of the generic type definition.

GetField(String, BindingFlags) GetField(String, BindingFlags) GetField(String, BindingFlags) GetField(String, BindingFlags)

指定した名前で指定されたフィールドを返します。Returns the field specified by the given name.

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);
override this.GetField : string * System.Reflection.BindingFlags -> System.Reflection.FieldInfo
Public Overrides Function GetField (name As String, bindingAttr As BindingFlags) As FieldInfo

パラメーター

name
String String String String

取得するフィールドの名前。The name of the field to get.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

これは InvokeMethodNonPublic などにある、BindingFlags からのビット フラグでなければなりません。This must be a bit flag from BindingFlags as in InvokeMethod, NonPublic, and so on.

戻り値

指定した名前と公開または非公開の修飾子を持つ、この型によって宣言または継承されているフィールドを表す FieldInfo オブジェクトを返します。Returns the FieldInfo object representing the field declared or inherited by this type with the specified name and public or non-public modifier. 一致するものがない場合は、null が返されます。If there are no matches then null is returned.

例外

不完全な型では、このメソッドは実装されません。This method is not implemented for incomplete types.

注釈

使用して型を取得Type.GetTypeまたはAssembly.GetTypeし、取得した型に対してリフレクションを使用します。Retrieve the type using Type.GetType or Assembly.GetType and use reflection on the retrieved type.

GetField(Type, FieldInfo) GetField(Type, FieldInfo) GetField(Type, FieldInfo)

ジェネリック型定義の指定されたフィールドに対応する、指定の構築されたジェネリック型のフィールドを返します。Returns the field of the specified constructed generic type that corresponds to the specified field of the generic type definition.

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

パラメーター

type
Type Type Type Type

フィールドが返される構築されたジェネリック型。The constructed generic type whose field is returned.

field
FieldInfo FieldInfo FieldInfo FieldInfo

返す type のフィールドを指定する、type のジェネリック型定義のフィールド。A field on the generic type definition of type, which specifies which field of type to return.

戻り値

type のジェネリック型定義に属するフィールドを指定する、field に対応する type のフィールドを表す FieldInfo オブジェクト。A FieldInfo object that represents the field of type corresponding to field, which specifies a field belonging to the generic type definition of type.

例外

type がジェネリック型を表していません。type does not represent a generic type.

または-or- typeTypeBuilder 型ではありません。type is not of type TypeBuilder.

または-or- field の宣言する型はジェネリック型定義ではありません。The declaring type of field is not a generic type definition.

または-or- field の宣言する型は type のジェネリック型定義ではありません。The declaring type of field is not the generic type definition of type.

次のコード例には、という名前の型パラメーターを持つサンプルによってという名前のジェネリック クラスのソース コードが含まれています。Tします。The following code example contains source code for a generic class named Sample that has a type parameter named T. という名前のフィールドをクラスにはField、型のT、という名前のジェネリック メソッドGMという名前の独自の型パラメーターを持つUします。The class has a field named Field, of type T, and a generic method named GM with its own type parameter, named U. メソッドGMのインスタンスを作成しますSample、独自の型パラメーターの置換Uの型パラメーターに対してSample、し、その入力パラメーターを格納Fieldします。Method GM creates an instance of Sample, substituting its own type parameter U for the type parameter of Sample, and stores its input parameter in Field. このソース コードはコンパイルされますが、使用されません。表示できます、 Ildasm.exe (IL Disassembler)クラスによって出力されるコードとの比較とExampleします。This source code is compiled but not used; you can view it with the Ildasm.exe (IL Disassembler) and compare it to the code emitted by class Example.

クラスのコードExampleの使用方法を示します、GetFieldジェネリック コードを出力するメソッド。The code in class Example demonstrates the use of the GetField method to emit generic code. MainクラスのメソッドExampleという名前のクラスを含む動的アセンブリを作成します。 Sample、を使用して、DefineGenericParametersメソッドという名前の型パラメーターを追加することで汎用的なものをTします。The Main method of class Example creates a dynamic assembly containing a class named Sample, and uses the DefineGenericParameters method to make it generic by adding a type parameter named T. 既定のコンス トラクターとという名前のフィールドField、型のT、クラスに追加されますSampleします。A default constructor and a field named Field, of type T, are added to class Sample. メソッドGMが追加されを使用してジェネリック メソッドに変換、MethodBuilder.DefineGenericParametersメソッド。A method GM is added and turned into a generic method by using the MethodBuilder.DefineGenericParameters method. 型パラメーターGMというUします。The type parameter of GM is named U. 型パラメーターを定義すると後のシグネチャGMを使用して追加、MethodBuilder.SetSignatureメソッド。After the type parameter is defined, the signature of GM is added by using the MethodBuilder.SetSignature method. 戻り値の型と必要ありませんが、またはカスタム修飾子は、このメソッドのすべてのパラメーターは、nullを除くparameterTypes;parameterTypesにメソッドの唯一のパラメーターの型を設定Uメソッドのジェネリック型パラメーター。There is no return type and no required or custom modifiers, so all the parameters of this method are null except parameterTypes; parameterTypes sets the type of the method's only parameter to U, the method's generic type parameter. メソッドの本体は、構築された型のインスタンスを作成します。 Sample<U> (Sample(Of U) Visual basic)、メソッドのパラメーターに割り当てますField、しの値を出力しますFieldします。The body of the method creates an instance of the constructed type Sample<U> (Sample(Of U) in Visual Basic), assigns the method's parameter to Field, and then prints the value of Field. GetFieldメソッドの使用を作成、FieldInfo構築されたジェネリック型のフィールドを表すSample<U>で、OpCodes.StfldOpCodes.Ldfld指示します。The GetField method is used to create a FieldInfo that represents the field of the constructed generic type Sample<U> in the OpCodes.Stfld and OpCodes.Ldfld instructions.

エントリ ポイント メソッドを保持するためにダミーの型が定義されているMainします。A dummy type is defined to hold the entry-point method Main. 本体でMain、静的なGM構築されたジェネリック型のメソッドが呼び出されるSample<int>(Sample(Of Integer) Visual Basic で)、型のStringの代わりに使用Uします。In the body of Main, the static GM method is invoked on the constructed generic type Sample<int> (Sample(Of Integer) in Visual Basic), with type String substituted for U.

コード例を実行すると、TypeBuilderGetFieldExample.exe として生成されたアセンブリが保存されます。When the code example is run, it saves the emitted assembly as TypeBuilderGetFieldExample.exe. TypeBuilderGetFieldExample.exe を実行して、使用することができます、 Ildasm.exe (IL Disassembler) 、出力コードのコードを比較する、Sample自体のコード例にコンパイルされるクラス。You can run TypeBuilderGetFieldExample.exe, and you can use the Ildasm.exe (IL Disassembler) to compare the emitted code with the code for the Sample class that is compiled into the code example itself.

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
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 

注釈

GetFieldメソッドを取得する方法を提供する、FieldInfoでジェネリック型定義が表される構築されたジェネリック型のフィールドを表すオブジェクトをTypeBuilderオブジェクト。The GetField method provides a way to get a FieldInfo object that represents a field of a constructed generic type whose generic type definition is represented by a TypeBuilder object.

などがあるとします、TypeBuilderオブジェクト型を表すG<T>c# 構文で (G(Of T) Visual basic でgeneric <T> ref class GC++ で)、FieldBuilderフィールドを表すオブジェクトをpublic T Fc# 構文で (Public F As TVisual basic でpublic: T FC++ で) で定義されているG<T>します。For example, suppose you have a TypeBuilder object that represents the type G<T> in C# syntax (G(Of T) in Visual Basic, generic <T> ref class G in C++) and a FieldBuilder object that represents a field public T F in C# syntax (Public F As T in Visual Basic, public: T F in C++) that is defined by G<T>. ものとしますG<T>ジェネリック型パラメーターを持つメソッドがありますU構築された型のインスタンスを作成するG<U>と呼び出しフィールドFそのインスタンスにします。Suppose that G<T> has a generic method with type parameter U that creates an instance of the constructed type G<U> and calls field F on that instance. 関数呼び出しを生成するためにする必要があります、FieldInfoを表すオブジェクトをFで構築された型、つまり、上で、型のU型ではなくTします。In order to emit the function call, you need a FieldInfo object that represents F on the constructed type - in other words, that is of type U rather than type T. これを行うには、最初に呼び出す、MakeGenericTypeメソッドをTypeBuilderオブジェクトを指定する、GenericTypeParameterBuilderを表すオブジェクトをU型引数として。To do this, first call the MakeGenericType method on the TypeBuilder object, specifying the GenericTypeParameterBuilder object that represents U as the type argument. 呼び出して、GetFieldメソッドの戻り値をMakeGenericTypeメソッド パラメーターとしてtypeFieldBuilderを表すオブジェクトをFパラメーターとしてfieldします。Then call the GetField method with the return value of the MakeGenericType method as parameter type and the FieldBuilder object that represents F as parameter field. 戻り値は、FieldInfoオブジェクト、関数呼び出しを生成する必要があります。The return value is the FieldInfo object you need to emit the function call. コード例では、このシナリオを示します。The code example demonstrates this scenario.

適用対象