TypeBuilder.GetField 메서드

정의

현재 TypeBuilder에 의해 정의된 필드를 반환합니다.

오버로드

GetField(Type, FieldInfo)

제네릭 형식 정의의 지정된 필드에 해당하는 생성된 특정 제네릭 형식의 필드를 반환합니다.

GetField(String, BindingFlags)

지정된 이름에 지정된 필드를 반환합니다.

GetField(Type, FieldInfo)

Source:
TypeBuilder.cs
Source:
RuntimeTypeBuilder.cs
Source:
TypeBuilder.cs

제네릭 형식 정의의 지정된 필드에 해당하는 생성된 특정 제네릭 형식의 필드를 반환합니다.

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

매개 변수

type
Type

해당 필드가 반환되는 생성된 제네릭 형식입니다.

field
FieldInfo

type 제네릭 형식 정의에 있는 필드로, 반환할 type 필드를 지정합니다.

반환

type의 제네릭 형식 정의에 속하는 필드를 지정하는 field에 해당하는 type의 필드를 나타내는 FieldInfo 개체입니다.

예외

type이 제네릭 형식을 나타내지 않습니다.

또는

typeTypeBuilder형식이 아닌 경우

또는

field의 선언 형식이 제네릭 형식 정의가 아닙니다.

또는

field의 선언 형식이 type의 제네릭 형식 정의가 아닙니다.

예제

다음 코드 예제에는 라는 T형식 매개 변수가 있는 Sample이라는 제네릭 클래스에 대한 소스 코드가 포함되어 있습니다. 클래스에는 형식의 라는 Field필드와 라는 고유한 형식 매개 변수를 사용하여 명명된 GM 제네릭 메서드가 있습니다U.T 메서드 GM 는 의 instance 만들고 의 Sample형식 매개 변수에 대해 고유한 형식 매개 변수 U 를 대체하고 입력 매개 Sample변수를 에 Field저장합니다. 이 소스 코드는 컴파일되었지만 사용되지 않습니다. Ildasm.exe(IL 디스어셈블러)로 보고 클래스 Example에서 내보낸 코드와 비교할 수 있습니다.

클래스 Example 의 코드는 메서드를 사용하여 GetField 제네릭 코드를 내보내는 방법을 보여 줍니다. 클래스 Example 의 메서드는 Main 라는 Sample클래스를 포함하는 동적 어셈블리를 만들고 메서드를 DefineGenericParameters 사용하여 라는 T형식 매개 변수를 추가하여 제네릭으로 만듭니다. 매개 변수가 없는 생성자와 형식의 T라는 Field필드가 클래스 Sample에 추가됩니다. 메서드가 추가되고 메서드 GM 를 사용하여 제네릭 메서드로 전환됩니다 MethodBuilder.DefineGenericParameters . 의 GM 형식 매개 변수 이름은 U입니다. 형식 매개 변수가 정의되면 메서드를 사용하여 의 GM 서명이 MethodBuilder.SetSignature 추가됩니다. 반환 형식이 없고 필수 또는 사용자 지정 한정자가 없으므로 이 메서드의 모든 매개 변수는 nullparameterTypes 제외하고 parameterTypes메서드의 유일한 매개 변수 형식을 U로 설정합니다. 메서드의 제네릭 형식 매개 변수입니다. 메서드 본문은 생성된 형식 Sample<U> (Visual Basic의 경우)Sample(Of U)의 instance 만들고 메서드의 매개 변수를 Field에 할당한 다음 값을 Field출력합니다. 메서드는 GetFieldOpCodes.Ldfld 명령에서 생성된 제네릭 형식 Sample<U> 의 필드를 나타내는 을 OpCodes.Stfld 만드는 FieldInfo 데 사용됩니다.

더미 형식은 진입점 메서드 Main를 포함하도록 정의됩니다. 본 Main문에서 정적 GM 메서드는 생성된 제네릭 형식 Sample<int> (Visual Basic의 경우)Sample(Of Integer) 에서 호출되고 형식 String 은 로 U대체됩니다.

코드 예제가 실행되면 내보낸 어셈블리를 TypeBuilderGetFieldExample.exe 저장합니다. TypeBuilderGetFieldExample.exe 실행할 수 있으며 ,Ildasm.exe(IL 디스어셈블러)를 사용하여 내보낸 코드를 코드 예제 자체로 컴파일된 클래스의 Sample 코드와 비교할 수 있습니다.

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

설명

메서드는 GetField 제네릭 형식 정의가 개체로 FieldInfo 표현되는 생성된 제네릭 형식의 필드를 나타내는 개체를 TypeBuilder 가져오는 방법을 제공합니다.

예를 들어 C# 구문(G(Of T)Visual Basic의 generic <T> ref class G 경우 TypeBuilder C++) 형식 G<T> 을 나타내는 개체와 FieldBuilder 에서 정의G<T>한 C# 구문(Public F As TVisual Basic의 public: T F 경우 C++)의 필드를 public T F 나타내는 개체가 있다고 가정합니다. G<T> 생성된 형식의 instance 만들고 해당 instance 필드를 F 호출하는 형식 매개 G<U> 변수 U 가 있는 제네릭 메서드가 있다고 가정합니다. 함수 호출을 내보내려면 생성된 형식을 나타내는 개체가 필요합니다FieldInfo. F 즉, 형식T이 아닌 형식 U 입니다. 이렇게 하려면 먼저 형식 인수로 나타내는 개체를 TypeBuilder 지정하여 GenericTypeParameterBuilder 개체에서 메서드를 호출 MakeGenericType 합니다U. 그런 다음 메서드의 반환 값을 MakeGenericType 매개 변수로, FieldBuilder 를 매개 변수 typefield로 나타내는 개체를 사용하여 메서드를 호출합니다F.GetField 반환 값은 함수 호출을 내보내는 데 필요한 개체입니다 FieldInfo . 코드 예제에서는 이 시나리오를 보여 줍니다.

적용 대상

GetField(String, BindingFlags)

Source:
TypeBuilder.cs

지정된 이름에 지정된 필드를 반환합니다.

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

매개 변수

name
String

가져올 필드의 이름입니다.

bindingAttr
BindingFlags

이는 InvokeMethod, NonPublic 등에서처럼 BindingFlags의 비트 플래그여야 합니다.

반환

public 또는 non-public 한정자와 지정된 이름을 사용하여 이 형식에 의해 선언되거나 상속된 필드를 나타내는 FieldInfo 개체를 반환합니다. 일치하는 항목이 없으면 null이 반환됩니다.

예외

이 메서드는 불완전한 형식에 대해 구현되지 않습니다.

설명

또는 Assembly.GetType 를 사용하여 Type.GetType 형식을 검색하고 검색된 형식에서 리플렉션을 사용합니다.

적용 대상