TypeBuilder.GetField Metódus
Definíció
Fontos
Egyes információk olyan, kiadás előtti termékekre vonatkoznak, amelyek a kiadásig még jelentősen módosulhatnak. A Microsoft nem vállal kifejezett vagy törvényi garanciát az itt megjelenő információért.
Az aktuális TypeBuilderáltal meghatározott mezőt ad vissza.
Túlterhelések
| Name | Description |
|---|---|
| GetField(Type, FieldInfo) |
A megadott konstruktált általános típus azon mezőjét adja vissza, amely megfelel az általános típusdefiníció megadott mezőjének. |
| GetField(String, BindingFlags) |
A megadott név által megadott mezőt adja vissza. |
GetField(Type, FieldInfo)
- Forrás:
- TypeBuilder.cs
- Forrás:
- TypeBuilder.cs
- Forrás:
- TypeBuilder.cs
- Forrás:
- RuntimeTypeBuilder.cs
- Forrás:
- TypeBuilder.cs
A megadott konstruktált általános típus azon mezőjét adja vissza, amely megfelel az általános típusdefiníció megadott mezőjének.
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
Paraméterek
- type
- Type
Az a konstruktált általános típus, amelynek a mezőjét a rendszer visszaadja.
- field
- FieldInfo
A visszatérési mező az általános típusdefinícióban type, amely meghatározza, hogy melyik mezőt type adja vissza.
Válaszok
Olyan FieldInfo objektum, amely a megfelelő mezőnek type felel fieldmeg, amely a általános típusdefiníciójának typemegfelelő mezőt adja meg.
Kivételek
type nem általános típust jelöl.
-vagy-
type nem típus TypeBuilder.
-vagy-
A deklarálási field típus nem általános típusdefiníció.
-vagy-
A deklarálási field típus nem az általános típusdefiníciója type.
Példák
Az alábbi példakód egy minta nevű általános osztály forráskódját tartalmazza, amelynek típusparamétere neve T. Az osztálynak van egy , type Fieldnevű Tmezője és egy saját típusparaméterrel elnevezett GM általános metódusa.U A metódus GM létrehoz egy példányt Sample, amely a saját típusparaméterét U helyettesíti a típusparaméterhez Sample, és a bemeneti paramétert a következőben Fieldtárolja: . Ezt a forráskódot lefordítottuk, de nem használjuk; megtekintheti a Ildasm.exe (IL-szétszereléssel), és összehasonlíthatja az osztály Exampleáltal kibocsátott kóddal.
Az osztályban Example lévő kód bemutatja, hogy a GetField metódus általános kódot bocsát ki. Az Main osztály Example metódusa létrehoz egy dinamikus szerelvényt, amely egy nevesített Sampleosztályt tartalmaz, és a DefineGenericParameters metódus használatával általánossá teszi egy névvel ellátott Ttípusparaméter hozzáadásával. A rendszer hozzáad egy paraméter nélküli konstruktort és egy típus Fieldnevű Tmezőt az osztályhozSample. A metódussal hozzáadunk egy metódustGM, és általános metódussá alakítjuk.MethodBuilder.DefineGenericParameters A típusparaméter neve GMU. A típusparaméter definiálása után a rendszer hozzáadja az aláírást GM a MethodBuilder.SetSignature metódus használatával. Nincs visszatérési típus, és nincs szükség vagy egyéni módosítók, ezért a metódus null összes paramétere kivételt képez parameterTypes; parameterTypes a metódus egyetlen paraméterének Utípusát állítja be a metódus általános típusparaméterére. A metódus törzse létrehozza a létrehozott Sample<U> (Sample(Of U) Visual Basic) típusú példányt, hozzárendeli a metódus paraméterét Field, majd kinyomtatja a Field értékét. A GetField metódussal létrehozunk egy FieldInfo olyan mezőt, amely a konstruktált általános típus Sample<U> mezőjét jelöli az utasításokban és OpCodes.Stfld az OpCodes.Ldfld utasításokban.
A belépési pont metódusának Maintárolására egy próbabábutípus van definiálva. A Main törzsében a statikus GM metódus a Sample<int> (Sample(Of Integer) Visual Basic) általános típuson lesz meghívva, StringU típus helyett.
A példakód futtatásakor a rendszer menti a kibocsátott szerelvényt TypeBuilderGetFieldExample.exe. Futtathat TypeBuilderGetFieldExample.exe, és a Ildasm.exe (IL Disassembler) használatával összehasonlíthatja a kibocsátott kódot a Sample kód példájába lefordított osztály kódjával.
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
Megjegyzések
A GetField módszer lehetővé teszi egy olyan objektum lekérését FieldInfo , amely egy olyan általános típusú, általános típusú mezőt jelöl, amelynek általános típusdefinícióját egy TypeBuilder objektum képviseli.
Tegyük fel például, hogy van egy G<T> egy általános metódus típusparaméterrel U rendelkezik, amely létrehozza a létrehozott típus G<U> egy példányát, és meghívja a mezőt F az adott példányon. A függvényhívás kibocsátásához egy FieldInfo olyan objektumra van szükség, amely a létrehozott típuson van jelölve F – más szóval, hogy nem típus, hanem típus UT. Ehhez először hívja meg az MakeGenericType objektum metódusát TypeBuilder , és adja meg a GenericTypeParameterBuilder típusargumentumként megjelenő U objektumot. Ezután hívja meg a GetField metódust paraméterként MakeGenericType a metódus visszatérési értékével type és a FieldBuilder paraméterként Fmegjelenő field objektummal. A visszatérési érték az az FieldInfo objektum, amelyet ki kell bocsátania a függvényhívásból. A példakód ezt a forgatókönyvet mutatja be.
A következőre érvényes:
GetField(String, BindingFlags)
- Forrás:
- TypeBuilder.cs
A megadott név által megadott mezőt adja vissza.
public:
override System::Reflection::FieldInfo ^ GetField(System::String ^ name, System::Reflection::BindingFlags bindingAttr);
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields)]
public override System.Reflection.FieldInfo? GetField(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);
[<System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.NonPublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields)>]
override this.GetField : string * System.Reflection.BindingFlags -> System.Reflection.FieldInfo
override this.GetField : string * System.Reflection.BindingFlags -> System.Reflection.FieldInfo
Public Overrides Function GetField (name As String, bindingAttr As BindingFlags) As FieldInfo
Paraméterek
- name
- String
A lekérendő mező neve.
- bindingAttr
- BindingFlags
Ennek egy kis jelölőnek kell lennie a következőtől BindingFlagsInvokeMethodkezdveNonPublic, és így tovább.
Válaszok
FieldInfo Az ilyen típus által deklarált vagy örökölt mezőt képviselő objektumot adja vissza a megadott névvel és nyilvános vagy nem nyilvános módosítóval. Ha nincsenek egyezések, akkor null a rendszer visszaadja.
- Attribútumok
Kivételek
Ez a metódus nem hiányos típusok esetén van implementálva.
Megjegyzések
Kérje le a típust a lekért típussal Type.GetType , vagy Assembly.GetType használja a visszaverődést a beolvasott típuson.