TypeBuilder Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Définit et crée de nouvelles instances de classes pendant l’exécution.
public ref class TypeBuilder sealed : Type, System::Runtime::InteropServices::_TypeBuilder
public ref class TypeBuilder sealed : System::Reflection::TypeInfo, System::Runtime::InteropServices::_TypeBuilder
public ref class TypeBuilder sealed : Type
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
public sealed class TypeBuilder : Type, System.Runtime.InteropServices._TypeBuilder
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class TypeBuilder : Type, System.Runtime.InteropServices._TypeBuilder
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class TypeBuilder : System.Reflection.TypeInfo, System.Runtime.InteropServices._TypeBuilder
public sealed class TypeBuilder : Type
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
type TypeBuilder = class
inherit Type
interface _TypeBuilder
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type TypeBuilder = class
inherit Type
interface _TypeBuilder
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type TypeBuilder = class
inherit TypeInfo
interface _TypeBuilder
type TypeBuilder = class
inherit Type
Public NotInheritable Class TypeBuilder
Inherits Type
Implements _TypeBuilder
Public NotInheritable Class TypeBuilder
Inherits TypeInfo
Implements _TypeBuilder
Public NotInheritable Class TypeBuilder
Inherits Type
- Héritage
- Héritage
- Attributs
- Implémente
Exemples
L’exemple de code suivant montre comment définir et utiliser un assembly dynamique. L’exemple d’assembly contient un type, MyDynamicTypequi a un champ privé, une propriété qui obtient et définit le champ privé, les constructeurs qui initialisent le champ privé et une méthode qui multiplie un nombre fourni par l’utilisateur par la valeur de champ privé et retourne le résultat.
using System;
using System.Reflection;
using System.Reflection.Emit;
class DemoAssemblyBuilder
{
public static void Main()
{
// This code creates an assembly that contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In C# the type might look like this:
/*
public class MyDynamicType
{
private int m_number;
public MyDynamicType() : this(42) {}
public MyDynamicType(int initNumber)
{
m_number = initNumber;
}
public int Number
{
get { return m_number; }
set { m_number = value; }
}
public int MyMethod(int multiplier)
{
return m_number * multiplier;
}
}
*/
var aName = new AssemblyName("DynamicAssemblyExample");
AssemblyBuilder ab =
AssemblyBuilder.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.Run);
// The module name is usually the same as the assembly name.
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name ?? "DynamicAssemblyExample");
TypeBuilder tb = mb.DefineType(
"MyDynamicType",
TypeAttributes.Public);
// Add a private field of type int (Int32).
FieldBuilder fbNumber = tb.DefineField(
"m_number",
typeof(int),
FieldAttributes.Private);
// Define a constructor that takes an integer argument and
// stores it in the private field.
Type[] parameterTypes = { typeof(int) };
ConstructorBuilder ctor1 = tb.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
parameterTypes);
ILGenerator ctor1IL = ctor1.GetILGenerator();
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before calling the base
// class constructor. Specify the default constructor of the
// base class (System.Object) by passing an empty array of
// types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0);
ConstructorInfo? ci = typeof(object).GetConstructor(Type.EmptyTypes);
ctor1IL.Emit(OpCodes.Call, ci!);
// Push the instance on the stack before pushing the argument
// that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0);
ctor1IL.Emit(OpCodes.Ldarg_1);
ctor1IL.Emit(OpCodes.Stfld, fbNumber);
ctor1IL.Emit(OpCodes.Ret);
// Define a default constructor that supplies a default value
// for the private field. For parameter types, pass the empty
// array of types or pass null.
ConstructorBuilder ctor0 = tb.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
Type.EmptyTypes);
ILGenerator ctor0IL = ctor0.GetILGenerator();
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before pushing the default
// value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0);
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42);
ctor0IL.Emit(OpCodes.Call, ctor1);
ctor0IL.Emit(OpCodes.Ret);
// Define a property named Number that gets and sets the private
// field.
//
// The last argument of DefineProperty is null, because the
// property has no parameters. (If you don't specify null, you must
// specify an array of Type objects. For a parameterless property,
// use the built-in array with no elements: Type.EmptyTypes)
PropertyBuilder pbNumber = tb.DefineProperty(
"Number",
PropertyAttributes.HasDefault,
typeof(int),
null);
// The property "set" and property "get" methods require a special
// set of attributes.
MethodAttributes getSetAttr = MethodAttributes.Public |
MethodAttributes.SpecialName | MethodAttributes.HideBySig;
// Define the "get" accessor method for Number. The method returns
// an integer and has no arguments. (Note that null could be
// used instead of Types.EmptyTypes)
MethodBuilder mbNumberGetAccessor = tb.DefineMethod(
"get_Number",
getSetAttr,
typeof(int),
Type.EmptyTypes);
ILGenerator numberGetIL = mbNumberGetAccessor.GetILGenerator();
// For an instance property, argument zero is the instance. Load the
// instance, then load the private field and return, leaving the
// field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0);
numberGetIL.Emit(OpCodes.Ldfld, fbNumber);
numberGetIL.Emit(OpCodes.Ret);
// Define the "set" accessor method for Number, which has no return
// type and takes one argument of type int (Int32).
MethodBuilder mbNumberSetAccessor = tb.DefineMethod(
"set_Number",
getSetAttr,
null,
new Type[] { typeof(int) });
ILGenerator numberSetIL = mbNumberSetAccessor.GetILGenerator();
// Load the instance and then the numeric argument, then store the
// argument in the field.
numberSetIL.Emit(OpCodes.Ldarg_0);
numberSetIL.Emit(OpCodes.Ldarg_1);
numberSetIL.Emit(OpCodes.Stfld, fbNumber);
numberSetIL.Emit(OpCodes.Ret);
// Last, map the "get" and "set" accessor methods to the
// PropertyBuilder. The property is now complete.
pbNumber.SetGetMethod(mbNumberGetAccessor);
pbNumber.SetSetMethod(mbNumberSetAccessor);
// Define a method that accepts an integer argument and returns
// the product of that integer and the private field m_number. This
// time, the array of parameter types is created on the fly.
MethodBuilder meth = tb.DefineMethod(
"MyMethod",
MethodAttributes.Public,
typeof(int),
new Type[] { typeof(int) });
ILGenerator methIL = meth.GetILGenerator();
// To retrieve the private instance field, load the instance it
// belongs to (argument zero). After loading the field, load the
// argument one and then multiply. Return from the method with
// the return value (the product of the two numbers) on the
// execution stack.
methIL.Emit(OpCodes.Ldarg_0);
methIL.Emit(OpCodes.Ldfld, fbNumber);
methIL.Emit(OpCodes.Ldarg_1);
methIL.Emit(OpCodes.Mul);
methIL.Emit(OpCodes.Ret);
// Finish the type.
Type? t = tb.CreateType();
// Because AssemblyBuilderAccess includes Run, the code can be
// executed immediately. Start by getting reflection objects for
// the method and the property.
MethodInfo? mi = t?.GetMethod("MyMethod");
PropertyInfo? pi = t?.GetProperty("Number");
// Create an instance of MyDynamicType using the default
// constructor.
object? o1 = null;
if (t is not null)
o1 = Activator.CreateInstance(t);
// Display the value of the property, then change it to 127 and
// display it again. Use null to indicate that the property
// has no index.
Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null));
pi?.SetValue(o1, 127, null);
Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null));
// Call MyMethod, passing 22, and display the return value, 22
// times 127. Arguments must be passed as an array, even when
// there is only one.
object[] arguments = { 22 };
Console.WriteLine("o1.MyMethod(22): {0}",
mi?.Invoke(o1, arguments));
// Create an instance of MyDynamicType using the constructor
// that specifies m_Number. The constructor is identified by
// matching the types in the argument array. In this case,
// the argument array is created on the fly. Display the
// property value.
object? o2 = null;
if (t is not null)
o2 = Activator.CreateInstance(t, new object[] { 5280 });
Console.WriteLine("o2.Number: {0}", pi?.GetValue(o2, null));
}
}
/* This code produces the following output:
o1.Number: 42
o1.Number: 127
o1.MyMethod(22): 2794
o2.Number: 5280
*/
Imports System.Reflection
Imports System.Reflection.Emit
Class DemoAssemblyBuilder
Public Shared Sub Main()
' This code creates an assembly that contains one type,
' named "MyDynamicType", that has a private field, a property
' that gets and sets the private field, constructors that
' initialize the private field, and a method that multiplies
' a user-supplied number by the private field value and returns
' the result. The code might look like this in Visual Basic:
'
'Public Class MyDynamicType
' Private m_number As Integer
'
' Public Sub New()
' Me.New(42)
' End Sub
'
' Public Sub New(ByVal initNumber As Integer)
' m_number = initNumber
' End Sub
'
' Public Property Number As Integer
' Get
' Return m_number
' End Get
' Set
' m_Number = Value
' End Set
' End Property
'
' Public Function MyMethod(ByVal multiplier As Integer) As Integer
' Return m_Number * multiplier
' End Function
'End Class
Dim aName As New AssemblyName("DynamicAssemblyExample")
Dim ab As AssemblyBuilder = _
AssemblyBuilder.DefineDynamicAssembly( _
aName, _
AssemblyBuilderAccess.Run)
' The module name is usually the same as the assembly name.
Dim mb As ModuleBuilder = ab.DefineDynamicModule( _
aName.Name)
Dim tb As TypeBuilder = _
mb.DefineType("MyDynamicType", TypeAttributes.Public)
' Add a private field of type Integer (Int32).
Dim fbNumber As FieldBuilder = tb.DefineField( _
"m_number", _
GetType(Integer), _
FieldAttributes.Private)
' Define a constructor that takes an integer argument and
' stores it in the private field.
Dim parameterTypes() As Type = { GetType(Integer) }
Dim ctor1 As ConstructorBuilder = _
tb.DefineConstructor( _
MethodAttributes.Public, _
CallingConventions.Standard, _
parameterTypes)
Dim ctor1IL As ILGenerator = ctor1.GetILGenerator()
' For a constructor, argument zero is a reference to the new
' instance. Push it on the stack before calling the base
' class constructor. Specify the default constructor of the
' base class (System.Object) by passing an empty array of
' types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Call, _
GetType(Object).GetConstructor(Type.EmptyTypes))
' Push the instance on the stack before pushing the argument
' that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Ldarg_1)
ctor1IL.Emit(OpCodes.Stfld, fbNumber)
ctor1IL.Emit(OpCodes.Ret)
' Define a default constructor that supplies a default value
' for the private field. For parameter types, pass the empty
' array of types or pass Nothing.
Dim ctor0 As ConstructorBuilder = tb.DefineConstructor( _
MethodAttributes.Public, _
CallingConventions.Standard, _
Type.EmptyTypes)
Dim ctor0IL As ILGenerator = ctor0.GetILGenerator()
' For a constructor, argument zero is a reference to the new
' instance. Push it on the stack before pushing the default
' value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0)
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42)
ctor0IL.Emit(OpCodes.Call, ctor1)
ctor0IL.Emit(OpCodes.Ret)
' Define a property named Number that gets and sets the private
' field.
'
' The last argument of DefineProperty is Nothing, because the
' property has no parameters. (If you don't specify Nothing, you must
' specify an array of Type objects. For a parameterless property,
' use the built-in array with no elements: Type.EmptyTypes)
Dim pbNumber As PropertyBuilder = tb.DefineProperty( _
"Number", _
PropertyAttributes.HasDefault, _
GetType(Integer), _
Nothing)
' The property Set and property Get methods require a special
' set of attributes.
Dim getSetAttr As MethodAttributes = _
MethodAttributes.Public Or MethodAttributes.SpecialName _
Or MethodAttributes.HideBySig
' Define the "get" accessor method for Number. The method returns
' an integer and has no arguments. (Note that Nothing could be
' used instead of Types.EmptyTypes)
Dim mbNumberGetAccessor As MethodBuilder = tb.DefineMethod( _
"get_Number", _
getSetAttr, _
GetType(Integer), _
Type.EmptyTypes)
Dim numberGetIL As ILGenerator = mbNumberGetAccessor.GetILGenerator()
' For an instance property, argument zero is the instance. Load the
' instance, then load the private field and return, leaving the
' field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0)
numberGetIL.Emit(OpCodes.Ldfld, fbNumber)
numberGetIL.Emit(OpCodes.Ret)
' Define the "set" accessor method for Number, which has no return
' type and takes one argument of type Integer (Int32).
Dim mbNumberSetAccessor As MethodBuilder = _
tb.DefineMethod( _
"set_Number", _
getSetAttr, _
Nothing, _
New Type() { GetType(Integer) })
Dim numberSetIL As ILGenerator = mbNumberSetAccessor.GetILGenerator()
' Load the instance and then the numeric argument, then store the
' argument in the field.
numberSetIL.Emit(OpCodes.Ldarg_0)
numberSetIL.Emit(OpCodes.Ldarg_1)
numberSetIL.Emit(OpCodes.Stfld, fbNumber)
numberSetIL.Emit(OpCodes.Ret)
' Last, map the "get" and "set" accessor methods to the
' PropertyBuilder. The property is now complete.
pbNumber.SetGetMethod(mbNumberGetAccessor)
pbNumber.SetSetMethod(mbNumberSetAccessor)
' Define a method that accepts an integer argument and returns
' the product of that integer and the private field m_number. This
' time, the array of parameter types is created on the fly.
Dim meth As MethodBuilder = tb.DefineMethod( _
"MyMethod", _
MethodAttributes.Public, _
GetType(Integer), _
New Type() { GetType(Integer) })
Dim methIL As ILGenerator = meth.GetILGenerator()
' To retrieve the private instance field, load the instance it
' belongs to (argument zero). After loading the field, load the
' argument one and then multiply. Return from the method with
' the return value (the product of the two numbers) on the
' execution stack.
methIL.Emit(OpCodes.Ldarg_0)
methIL.Emit(OpCodes.Ldfld, fbNumber)
methIL.Emit(OpCodes.Ldarg_1)
methIL.Emit(OpCodes.Mul)
methIL.Emit(OpCodes.Ret)
' Finish the type.
Dim t As Type = tb.CreateType()
' Because AssemblyBuilderAccess includes Run, the code can be
' executed immediately. Start by getting reflection objects for
' the method and the property.
Dim mi As MethodInfo = t.GetMethod("MyMethod")
Dim pi As PropertyInfo = t.GetProperty("Number")
' Create an instance of MyDynamicType using the default
' constructor.
Dim o1 As Object = Activator.CreateInstance(t)
' Display the value of the property, then change it to 127 and
' display it again. Use Nothing to indicate that the property
' has no index.
Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))
pi.SetValue(o1, 127, Nothing)
Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))
' Call MyMethod, passing 22, and display the return value, 22
' times 127. Arguments must be passed as an array, even when
' there is only one.
Dim arguments() As Object = { 22 }
Console.WriteLine("o1.MyMethod(22): {0}", _
mi.Invoke(o1, arguments))
' Create an instance of MyDynamicType using the constructor
' that specifies m_Number. The constructor is identified by
' matching the types in the argument array. In this case,
' the argument array is created on the fly. Display the
' property value.
Dim o2 As Object = Activator.CreateInstance(t, _
New Object() { 5280 })
Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, Nothing))
End Sub
End Class
' This code produces the following output:
'
'o1.Number: 42
'o1.Number: 127
'o1.MyMethod(22): 2794
'o2.Number: 5280
L’exemple de code suivant montre comment générer un type dynamiquement à l’aide TypeBuilderde .
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
class TestILGenerator
{
public static Type DynamicDotProductGen()
{
Type ivType = null;
Type[] ctorParams = new Type[] { typeof(int),
typeof(int),
typeof(int)};
AppDomain myDomain = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName();
myAsmName.Name = "IntVectorAsm";
AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
myAsmName,
AssemblyBuilderAccess.RunAndSave);
ModuleBuilder IntVectorModule = myAsmBuilder.DefineDynamicModule("IntVectorModule",
"Vector.dll");
TypeBuilder ivTypeBld = IntVectorModule.DefineType("IntVector",
TypeAttributes.Public);
FieldBuilder xField = ivTypeBld.DefineField("x", typeof(int),
FieldAttributes.Private);
FieldBuilder yField = ivTypeBld.DefineField("y", typeof(int),
FieldAttributes.Private);
FieldBuilder zField = ivTypeBld.DefineField("z", typeof(int),
FieldAttributes.Private);
Type objType = Type.GetType("System.Object");
ConstructorInfo objCtor = objType.GetConstructor(new Type[0]);
ConstructorBuilder ivCtor = ivTypeBld.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
ctorParams);
ILGenerator ctorIL = ivCtor.GetILGenerator();
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Call, objCtor);
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_1);
ctorIL.Emit(OpCodes.Stfld, xField);
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_2);
ctorIL.Emit(OpCodes.Stfld, yField);
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_3);
ctorIL.Emit(OpCodes.Stfld, zField);
ctorIL.Emit(OpCodes.Ret);
// This method will find the dot product of the stored vector
// with another.
Type[] dpParams = new Type[] { ivTypeBld };
// Here, you create a MethodBuilder containing the
// name, the attributes (public, static, private, and so on),
// the return type (int, in this case), and a array of Type
// indicating the type of each parameter. Since the sole parameter
// is a IntVector, the very class you're creating, you will
// pass in the TypeBuilder (which is derived from Type) instead of
// a Type object for IntVector, avoiding an exception.
// -- This method would be declared in C# as:
// public int DotProduct(IntVector aVector)
MethodBuilder dotProductMthd = ivTypeBld.DefineMethod(
"DotProduct",
MethodAttributes.Public,
typeof(int),
dpParams);
// A ILGenerator can now be spawned, attached to the MethodBuilder.
ILGenerator mthdIL = dotProductMthd.GetILGenerator();
// Here's the body of our function, in MSIL form. We're going to find the
// "dot product" of the current vector instance with the passed vector
// instance. For reference purposes, the equation is:
// (x1 * x2) + (y1 * y2) + (z1 * z2) = the dot product
// First, you'll load the reference to the current instance "this"
// stored in argument 0 (ldarg.0) onto the stack. Ldfld, the subsequent
// instruction, will pop the reference off the stack and look up the
// field "x", specified by the FieldInfo token "xField".
mthdIL.Emit(OpCodes.Ldarg_0);
mthdIL.Emit(OpCodes.Ldfld, xField);
// That completed, the value stored at field "x" is now atop the stack.
// Now, you'll do the same for the object reference we passed as a
// parameter, stored in argument 1 (ldarg.1). After Ldfld executed,
// you'll have the value stored in field "x" for the passed instance
// atop the stack.
mthdIL.Emit(OpCodes.Ldarg_1);
mthdIL.Emit(OpCodes.Ldfld, xField);
// There will now be two values atop the stack - the "x" value for the
// current vector instance, and the "x" value for the passed instance.
// You'll now multiply them, and push the result onto the evaluation stack.
mthdIL.Emit(OpCodes.Mul_Ovf_Un);
// Now, repeat this for the "y" fields of both vectors.
mthdIL.Emit(OpCodes.Ldarg_0);
mthdIL.Emit(OpCodes.Ldfld, yField);
mthdIL.Emit(OpCodes.Ldarg_1);
mthdIL.Emit(OpCodes.Ldfld, yField);
mthdIL.Emit(OpCodes.Mul_Ovf_Un);
// At this time, the results of both multiplications should be atop
// the stack. You'll now add them and push the result onto the stack.
mthdIL.Emit(OpCodes.Add_Ovf_Un);
// Multiply both "z" field and push the result onto the stack.
mthdIL.Emit(OpCodes.Ldarg_0);
mthdIL.Emit(OpCodes.Ldfld, zField);
mthdIL.Emit(OpCodes.Ldarg_1);
mthdIL.Emit(OpCodes.Ldfld, zField);
mthdIL.Emit(OpCodes.Mul_Ovf_Un);
// Finally, add the result of multiplying the "z" fields with the
// result of the earlier addition, and push the result - the dot product -
// onto the stack.
mthdIL.Emit(OpCodes.Add_Ovf_Un);
// The "ret" opcode will pop the last value from the stack and return it
// to the calling method. You're all done!
mthdIL.Emit(OpCodes.Ret);
ivType = ivTypeBld.CreateType();
return ivType;
}
public static void Main() {
Type IVType = null;
object aVector1 = null;
object aVector2 = null;
Type[] aVtypes = new Type[] {typeof(int), typeof(int), typeof(int)};
object[] aVargs1 = new object[] {10, 10, 10};
object[] aVargs2 = new object[] {20, 20, 20};
// Call the method to build our dynamic class.
IVType = DynamicDotProductGen();
Console.WriteLine("---");
ConstructorInfo myDTctor = IVType.GetConstructor(aVtypes);
aVector1 = myDTctor.Invoke(aVargs1);
aVector2 = myDTctor.Invoke(aVargs2);
object[] passMe = new object[1];
passMe[0] = (object)aVector2;
Console.WriteLine("(10, 10, 10) . (20, 20, 20) = {0}",
IVType.InvokeMember("DotProduct",
BindingFlags.InvokeMethod,
null,
aVector1,
passMe));
// +++ OUTPUT +++
// ---
// (10, 10, 10) . (20, 20, 20) = 600
}
}
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
_
Class TestILGenerator
Public Shared Function DynamicDotProductGen() As Type
Dim ivType As Type = Nothing
Dim ctorParams() As Type = {GetType(Integer), GetType(Integer), GetType(Integer)}
Dim myDomain As AppDomain = Thread.GetDomain()
Dim myAsmName As New AssemblyName()
myAsmName.Name = "IntVectorAsm"
Dim myAsmBuilder As AssemblyBuilder = myDomain.DefineDynamicAssembly( _
myAsmName, _
AssemblyBuilderAccess.RunAndSave)
Dim IntVectorModule As ModuleBuilder = myAsmBuilder.DefineDynamicModule( _
"IntVectorModule", _
"Vector.dll")
Dim ivTypeBld As TypeBuilder = IntVectorModule.DefineType("IntVector", TypeAttributes.Public)
Dim xField As FieldBuilder = ivTypeBld.DefineField("x", _
GetType(Integer), _
FieldAttributes.Private)
Dim yField As FieldBuilder = ivTypeBld.DefineField("y", _
GetType(Integer), _
FieldAttributes.Private)
Dim zField As FieldBuilder = ivTypeBld.DefineField("z", _
GetType(Integer), _
FieldAttributes.Private)
Dim objType As Type = Type.GetType("System.Object")
Dim objCtor As ConstructorInfo = objType.GetConstructor(New Type() {})
Dim ivCtor As ConstructorBuilder = ivTypeBld.DefineConstructor( _
MethodAttributes.Public, _
CallingConventions.Standard, _
ctorParams)
Dim ctorIL As ILGenerator = ivCtor.GetILGenerator()
ctorIL.Emit(OpCodes.Ldarg_0)
ctorIL.Emit(OpCodes.Call, objCtor)
ctorIL.Emit(OpCodes.Ldarg_0)
ctorIL.Emit(OpCodes.Ldarg_1)
ctorIL.Emit(OpCodes.Stfld, xField)
ctorIL.Emit(OpCodes.Ldarg_0)
ctorIL.Emit(OpCodes.Ldarg_2)
ctorIL.Emit(OpCodes.Stfld, yField)
ctorIL.Emit(OpCodes.Ldarg_0)
ctorIL.Emit(OpCodes.Ldarg_3)
ctorIL.Emit(OpCodes.Stfld, zField)
ctorIL.Emit(OpCodes.Ret)
' Now, you'll construct the method find the dot product of two vectors. First,
' let's define the parameters that will be accepted by the method. In this case,
' it's an IntVector itself!
Dim dpParams() As Type = {ivTypeBld}
' Here, you create a MethodBuilder containing the
' name, the attributes (public, static, private, and so on),
' the return type (int, in this case), and a array of Type
' indicating the type of each parameter. Since the sole parameter
' is a IntVector, the very class you're creating, you will
' pass in the TypeBuilder (which is derived from Type) instead of
' a Type object for IntVector, avoiding an exception.
' -- This method would be declared in VB.NET as:
' Public Function DotProduct(IntVector aVector) As Integer
Dim dotProductMthd As MethodBuilder = ivTypeBld.DefineMethod("DotProduct", _
MethodAttributes.Public, GetType(Integer), _
dpParams)
' A ILGenerator can now be spawned, attached to the MethodBuilder.
Dim mthdIL As ILGenerator = dotProductMthd.GetILGenerator()
' Here's the body of our function, in MSIL form. We're going to find the
' "dot product" of the current vector instance with the passed vector
' instance. For reference purposes, the equation is:
' (x1 * x2) + (y1 * y2) + (z1 * z2) = the dot product
' First, you'll load the reference to the current instance "this"
' stored in argument 0 (ldarg.0) onto the stack. Ldfld, the subsequent
' instruction, will pop the reference off the stack and look up the
' field "x", specified by the FieldInfo token "xField".
mthdIL.Emit(OpCodes.Ldarg_0)
mthdIL.Emit(OpCodes.Ldfld, xField)
' That completed, the value stored at field "x" is now atop the stack.
' Now, you'll do the same for the object reference we passed as a
' parameter, stored in argument 1 (ldarg.1). After Ldfld executed,
' you'll have the value stored in field "x" for the passed instance
' atop the stack.
mthdIL.Emit(OpCodes.Ldarg_1)
mthdIL.Emit(OpCodes.Ldfld, xField)
' There will now be two values atop the stack - the "x" value for the
' current vector instance, and the "x" value for the passed instance.
' You'll now multiply them, and push the result onto the evaluation stack.
mthdIL.Emit(OpCodes.Mul_Ovf_Un)
' Now, repeat this for the "y" fields of both vectors.
mthdIL.Emit(OpCodes.Ldarg_0)
mthdIL.Emit(OpCodes.Ldfld, yField)
mthdIL.Emit(OpCodes.Ldarg_1)
mthdIL.Emit(OpCodes.Ldfld, yField)
mthdIL.Emit(OpCodes.Mul_Ovf_Un)
' At this time, the results of both multiplications should be atop
' the stack. You'll now add them and push the result onto the stack.
mthdIL.Emit(OpCodes.Add_Ovf_Un)
' Multiply both "z" field and push the result onto the stack.
mthdIL.Emit(OpCodes.Ldarg_0)
mthdIL.Emit(OpCodes.Ldfld, zField)
mthdIL.Emit(OpCodes.Ldarg_1)
mthdIL.Emit(OpCodes.Ldfld, zField)
mthdIL.Emit(OpCodes.Mul_Ovf_Un)
' Finally, add the result of multiplying the "z" fields with the
' result of the earlier addition, and push the result - the dot product -
' onto the stack.
mthdIL.Emit(OpCodes.Add_Ovf_Un)
' The "ret" opcode will pop the last value from the stack and return it
' to the calling method. You're all done!
mthdIL.Emit(OpCodes.Ret)
ivType = ivTypeBld.CreateType()
Return ivType
End Function 'DynamicDotProductGen
Public Shared Sub Main()
Dim IVType As Type = Nothing
Dim aVector1 As Object = Nothing
Dim aVector2 As Object = Nothing
Dim aVtypes() As Type = {GetType(Integer), GetType(Integer), GetType(Integer)}
Dim aVargs1() As Object = {10, 10, 10}
Dim aVargs2() As Object = {20, 20, 20}
' Call the method to build our dynamic class.
IVType = DynamicDotProductGen()
Dim myDTctor As ConstructorInfo = IVType.GetConstructor(aVtypes)
aVector1 = myDTctor.Invoke(aVargs1)
aVector2 = myDTctor.Invoke(aVargs2)
Console.WriteLine("---")
Dim passMe(0) As Object
passMe(0) = CType(aVector2, Object)
Console.WriteLine("(10, 10, 10) . (20, 20, 20) = {0}", _
IVType.InvokeMember("DotProduct", BindingFlags.InvokeMethod, _
Nothing, aVector1, passMe))
End Sub
End Class
' +++ OUTPUT +++
' ---
' (10, 10, 10) . (20, 20, 20) = 600
Remarques
Pour plus d’informations sur cette API, consultez les remarques d’API supplémentaires pour TypeBuilder.
Champs
| Nom | Description |
|---|---|
| UnspecifiedTypeSize |
Représente que la taille totale du type n’est pas spécifiée. |
Propriétés
| Nom | Description |
|---|---|
| Assembly |
Récupère l’assembly dynamique qui contient cette définition de type. |
| AssemblyQualifiedName |
Retourne le nom complet de ce type qualifié par le nom complet de l’assembly. |
| Attributes |
Obtient les attributs associés au Type. (Hérité de Type) |
| BaseType |
Récupère le type de base de ce type. |
| ContainsGenericParameters |
Obtient une valeur indiquant si l’objet Type actuel a des paramètres de type qui n’ont pas été remplacés par des types spécifiques. (Hérité de Type) |
| CustomAttributes |
Obtient une collection qui contient les attributs personnalisés de ce membre. (Hérité de MemberInfo) |
| DeclaredConstructors |
Obtient une collection des constructeurs déclarés par le type actuel. (Hérité de TypeInfo) |
| DeclaredEvents |
Obtient une collection des événements définis par le type actuel. (Hérité de TypeInfo) |
| DeclaredFields |
Obtient une collection des champs définis par le type actuel. (Hérité de TypeInfo) |
| DeclaredMembers |
Obtient une collection des membres définis par le type actuel. (Hérité de TypeInfo) |
| DeclaredMethods |
Obtient une collection des méthodes définies par le type actuel. (Hérité de TypeInfo) |
| DeclaredNestedTypes |
Obtient une collection des types imbriqués définis par le type actuel. (Hérité de TypeInfo) |
| DeclaredProperties |
Obtient une collection des propriétés définies par le type actuel. (Hérité de TypeInfo) |
| DeclaringMethod |
Obtient la méthode qui a déclaré le paramètre de type générique actuel. |
| DeclaringType |
Retourne le type qui a déclaré ce type. |
| FullName |
Récupère le chemin d’accès complet de ce type. |
| GenericParameterAttributes |
Obtient une valeur qui indique la covariance et les contraintes spéciales du paramètre de type générique actuel. |
| GenericParameterPosition |
Obtient la position d’un paramètre de type dans la liste des paramètres de type du type générique qui a déclaré le paramètre. |
| GenericTypeArguments |
Obtient un tableau des arguments de type générique pour ce type. (Hérité de Type) |
| GenericTypeParameters |
Obtient un tableau des paramètres de type générique de l’instance actuelle. (Hérité de TypeInfo) |
| GUID |
Récupère le GUID de ce type. |
| HasElementType |
Obtient une valeur indiquant si le Type actuel englobe ou fait référence à un autre type ; autrement dit, si le Type actuel est un tableau, un pointeur ou est passé par référence. (Hérité de Type) |
| ImplementedInterfaces |
Obtient une collection des interfaces implémentées par le type actuel. (Hérité de TypeInfo) |
| IsAbstract |
Obtient une valeur indiquant si le Type est abstrait et doit être substitué. (Hérité de Type) |
| IsAnsiClass |
Obtient une valeur indiquant si l’attribut de format de chaîne |
| IsArray |
Obtient une valeur qui indique si le type est un tableau. (Hérité de Type) |
| IsAutoClass |
Obtient une valeur indiquant si l’attribut de format de chaîne |
| IsAutoLayout |
Obtient une valeur indiquant si les champs du type actuel sont disposés automatiquement par le Common Language Runtime. (Hérité de Type) |
| IsByRef |
Obtient une valeur indiquant si la Type est passée par référence. (Hérité de Type) |
| IsByRefLike |
Obtient une valeur qui indique si le type est une structure de type byref. |
| IsClass |
Obtient une valeur indiquant si l'Type est une classe ou un délégué ; autrement dit, pas un type valeur ou une interface. (Hérité de Type) |
| IsCOMObject |
Obtient une valeur indiquant si le Type est un objet COM. (Hérité de Type) |
| IsConstructedGenericType |
Obtient une valeur qui indique si cet objet représente un type générique construit. |
| IsContextful |
Obtient une valeur indiquant si le Type peut être hébergé dans un contexte. (Hérité de Type) |
| IsEnum |
Obtient une valeur indiquant si le Type actuel représente une énumération. (Hérité de Type) |
| IsExplicitLayout |
Obtient une valeur indiquant si les champs du type actuel sont disposés à des décalages spécifiés explicitement. (Hérité de Type) |
| IsGenericMethodParameter |
Obtient une valeur qui indique si le Type actuel représente un paramètre de type dans la définition d’une méthode générique. (Hérité de Type) |
| IsGenericParameter |
Obtient une valeur indiquant si le type actuel est un paramètre de type générique. |
| IsGenericType |
Obtient une valeur indiquant si le type actuel est un type générique. |
| IsGenericTypeDefinition |
Obtient une valeur indiquant si le courant TypeBuilder représente une définition de type générique à partir de laquelle d’autres types génériques peuvent être construits. |
| IsGenericTypeParameter |
Obtient une valeur qui indique si le Type actuel représente un paramètre de type dans la définition d’un type générique. (Hérité de Type) |
| IsImport |
Obtient une valeur indiquant si l'Type a un attribut ComImportAttribute appliqué, indiquant qu’il a été importé à partir d’une bibliothèque de types COM. (Hérité de Type) |
| IsInterface |
Obtient une valeur indiquant si l'Type est une interface ; autrement dit, pas une classe ou un type valeur. (Hérité de Type) |
| IsLayoutSequential |
Obtient une valeur indiquant si les champs du type actuel sont disposés séquentiellement, dans l’ordre dans lequel ils ont été définis ou émis dans les métadonnées. (Hérité de Type) |
| IsMarshalByRef |
Obtient une valeur indiquant si le Type est marshalé par référence. (Hérité de Type) |
| IsNested |
Obtient une valeur indiquant si l’objet Type actuel représente un type dont la définition est imbriquée dans la définition d’un autre type. (Hérité de Type) |
| IsNestedAssembly |
Obtient une valeur indiquant si la Type est imbriquée et visible uniquement dans son propre assembly. (Hérité de Type) |
| IsNestedFamANDAssem |
Obtient une valeur indiquant si la Type est imbriquée et visible uniquement aux classes qui appartiennent à sa propre famille et à son propre assembly. (Hérité de Type) |
| IsNestedFamily |
Obtient une valeur indiquant si la Type est imbriquée et visible uniquement dans sa propre famille. (Hérité de Type) |
| IsNestedFamORAssem |
Obtient une valeur indiquant si la Type est imbriquée et visible uniquement aux classes qui appartiennent à sa propre famille ou à son propre assembly. (Hérité de Type) |
| IsNestedPrivate |
Obtient une valeur indiquant si la Type est imbriquée et déclarée privée. (Hérité de Type) |
| IsNestedPublic |
Obtient une valeur indiquant si une classe est imbriquée et déclarée publique. (Hérité de Type) |
| IsNotPublic |
Obtient une valeur indiquant si le Type n’est pas déclaré public. (Hérité de Type) |
| IsPointer |
Obtient une valeur indiquant si le Type est un pointeur. (Hérité de Type) |
| IsPrimitive |
Obtient une valeur indiquant si la Type est l’un des types primitifs. (Hérité de Type) |
| IsPublic |
Obtient une valeur indiquant si la Type est déclarée publique. (Hérité de Type) |
| IsSealed |
Obtient une valeur indiquant si la Type est déclarée scellée. (Hérité de Type) |
| IsSecurityCritical |
Obtient une valeur qui indique si le type actuel est critique pour la sécurité ou la sécurité et peut donc effectuer des opérations critiques. |
| IsSecuritySafeCritical |
Obtient une valeur qui indique si le type actuel est critique pour la sécurité ; autrement dit, qu’il puisse effectuer des opérations critiques et qu’il soit accessible par du code transparent. |
| IsSecurityTransparent |
Obtient une valeur qui indique si le type actuel est transparent et ne peut donc pas effectuer d’opérations critiques. |
| IsSerializable |
Obtient une valeur indiquant si le Type est sérialisable binaire. (Hérité de Type) |
| IsSignatureType |
Obtient une valeur qui indique si le type est un type de signature. (Hérité de Type) |
| IsSpecialName |
Obtient une valeur indiquant si le type a un nom qui nécessite une gestion spéciale. (Hérité de Type) |
| IsSZArray |
Définit et crée de nouvelles instances de classes pendant l’exécution. |
| IsTypeDefinition |
Définit et crée de nouvelles instances de classes pendant l’exécution. |
| IsUnicodeClass |
Obtient une valeur indiquant si l’attribut de format de chaîne |
| IsValueType |
Obtient une valeur indiquant si le Type est un type valeur. (Hérité de Type) |
| IsVariableBoundArray |
Définit et crée de nouvelles instances de classes pendant l’exécution. |
| IsVisible |
Obtient une valeur indiquant si le Type est accessible par du code en dehors de l’assembly. (Hérité de Type) |
| MemberType |
Obtient une valeur MemberTypes indiquant que ce membre est un type ou un type imbriqué. (Hérité de Type) |
| MetadataToken |
Obtient une valeur qui identifie un élément de métadonnées. (Hérité de MemberInfo) |
| Module |
Récupère le module dynamique qui contient cette définition de type. |
| Name |
Récupère le nom de ce type. |
| Namespace |
Récupère l’espace de noms où il |
| PackingSize |
Récupère la taille d’emballage de ce type. |
| ReflectedType |
Retourne le type utilisé pour obtenir ce type. |
| Size |
Récupère la taille totale d’un type. |
| StructLayoutAttribute |
Obtient une StructLayoutAttribute qui décrit la disposition du type actuel. (Hérité de Type) |
| TypeHandle |
Non pris en charge dans les modules dynamiques. |
| TypeInitializer |
Obtient l’initialiseur pour le type. (Hérité de Type) |
| TypeToken |
Retourne le jeton de type de ce type. |
| UnderlyingSystemType |
Retourne le type de système sous-jacent pour ce |
Méthodes
| Nom | Description |
|---|---|
| AddDeclarativeSecurity(SecurityAction, PermissionSet) |
Ajoute une sécurité déclarative à ce type. |
| AddInterfaceImplementation(Type) |
Ajoute une interface que ce type implémente. |
| AsType() |
Retourne le type actuel en tant qu’objet Type. (Hérité de TypeInfo) |
| CreateType() |
Crée un Type objet pour la classe. Après avoir défini des champs et des méthodes sur la classe, |
| CreateTypeInfo() |
Obtient un TypeInfo objet qui représente ce type. |
| DefineConstructor(MethodAttributes, CallingConventions, Type[], Type[][], Type[][]) |
Ajoute un nouveau constructeur au type, avec les attributs, la signature et les modificateurs personnalisés donnés. |
| DefineConstructor(MethodAttributes, CallingConventions, Type[]) |
Ajoute un nouveau constructeur au type, avec les attributs et la signature donnés. |
| DefineDefaultConstructor(MethodAttributes) |
Définit le constructeur sans paramètre. Le constructeur défini ici appelle simplement le constructeur sans paramètre du parent. |
| DefineEvent(String, EventAttributes, Type) |
Ajoute un nouvel événement au type, avec le nom, les attributs et le type d’événement donnés. |
| DefineField(String, Type, FieldAttributes) |
Ajoute un nouveau champ au type, avec le nom, les attributs et le type de champ donnés. |
| DefineField(String, Type, Type[], Type[], FieldAttributes) |
Ajoute un nouveau champ au type, avec le nom, les attributs, le type de champ et les modificateurs personnalisés donnés. |
| DefineGenericParameters(String[]) |
Définit les paramètres de type générique pour le type actuel, en spécifiant leur nombre et leurs noms, et retourne un tableau d’objets GenericTypeParameterBuilder qui peuvent être utilisés pour définir leurs contraintes. |
| DefineInitializedData(String, Byte[], FieldAttributes) |
Définit le champ de données initialisé dans la section .sdata du fichier exécutable portable (PE). |
| DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][]) |
Ajoute une nouvelle méthode au type, avec le nom spécifié, les attributs de méthode, la convention d’appel, la signature de méthode et les modificateurs personnalisés. |
| DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[]) |
Ajoute une nouvelle méthode au type, avec le nom, les attributs de méthode, la convention d’appel et la signature de méthode spécifiés. |
| DefineMethod(String, MethodAttributes, CallingConventions) |
Ajoute une nouvelle méthode au type, avec le nom, les attributs de méthode et la convention d’appel spécifiés. |
| DefineMethod(String, MethodAttributes, Type, Type[]) |
Ajoute une nouvelle méthode au type, avec le nom, les attributs de méthode et la signature de méthode spécifiés. |
| DefineMethod(String, MethodAttributes) |
Ajoute une nouvelle méthode au type, avec le nom et les attributs de méthode spécifiés. |
| DefineMethodOverride(MethodInfo, MethodInfo) |
Spécifie un corps de méthode donné qui implémente une déclaration de méthode donnée, potentiellement avec un autre nom. |
| DefineNestedType(String, TypeAttributes, Type, Int32) |
Définit un type imbriqué, en fonction de son nom, de ses attributs, de la taille totale du type et du type qu’il étend. |
| DefineNestedType(String, TypeAttributes, Type, PackingSize, Int32) |
Définit un type imbriqué, en fonction de son nom, de ses attributs, de sa taille et du type qu’il étend. |
| DefineNestedType(String, TypeAttributes, Type, PackingSize) |
Définit un type imbriqué, en fonction de son nom, de ses attributs, du type qu’il étend et de la taille d’emballage. |
| DefineNestedType(String, TypeAttributes, Type, Type[]) |
Définit un type imbriqué, en fonction de son nom, de ses attributs, du type qu’il étend et des interfaces qu’il implémente. |
| DefineNestedType(String, TypeAttributes, Type) |
Définit un type imbriqué, en fonction de son nom, de ses attributs et du type qu’il étend. |
| DefineNestedType(String, TypeAttributes) |
Définit un type imbriqué, en fonction de son nom et de ses attributs. |
| DefineNestedType(String) |
Définit un type imbriqué, en fonction de son nom. |
| DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Définit une |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet) |
Définit une |
| DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet) |
Définit une |
| DefineProperty(String, PropertyAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][]) |
Ajoute une nouvelle propriété au type, avec le nom donné, la convention d’appel, la signature de propriété et les modificateurs personnalisés. |
| DefineProperty(String, PropertyAttributes, CallingConventions, Type, Type[]) |
Ajoute une nouvelle propriété au type, avec le nom donné, les attributs, la convention d’appel et la signature de propriété. |
| DefineProperty(String, PropertyAttributes, Type, Type[], Type[], Type[], Type[][], Type[][]) |
Ajoute une nouvelle propriété au type, avec le nom donné, la signature de propriété et les modificateurs personnalisés. |
| DefineProperty(String, PropertyAttributes, Type, Type[]) |
Ajoute une nouvelle propriété au type, avec le nom et la signature de propriété donnés. |
| DefineTypeInitializer() |
Définit l’initialiseur pour ce type. |
| DefineUninitializedData(String, Int32, FieldAttributes) |
Définit un champ de données non initialisé dans la |
| Equals(Object) |
Détermine si le type système sous-jacent de l’objet Type actuel est identique au type de système sous-jacent du Objectspécifié. (Hérité de Type) |
| Equals(Type) |
Détermine si le type de système sous-jacent du Type actuel est identique au type de système sous-jacent du Typespécifié. (Hérité de Type) |
| FindInterfaces(TypeFilter, Object) |
Retourne un tableau d’objets Type représentant une liste filtrée d’interfaces implémentées ou héritées par la Typeactuelle. (Hérité de Type) |
| FindMembers(MemberTypes, BindingFlags, MemberFilter, Object) |
Retourne un tableau filtré d’objets MemberInfo du type de membre spécifié. (Hérité de Type) |
| GetArrayRank() |
Obtient le nombre de dimensions d’un tableau. (Hérité de Type) |
| GetAttributeFlagsImpl() |
En cas de substitution dans une classe dérivée, implémente la propriété Attributes et obtient une combinaison de valeurs d’énumération au niveau du bit qui indiquent les attributs associés au Type. (Hérité de Type) |
| GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
Recherche un constructeur dont les paramètres correspondent aux types d’arguments et modificateurs spécifiés, à l’aide des contraintes de liaison spécifiées et de la convention d’appel spécifiée. (Hérité de Type) |
| GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[]) |
Recherche un constructeur dont les paramètres correspondent aux types d’arguments et modificateurs spécifiés, à l’aide des contraintes de liaison spécifiées. (Hérité de Type) |
| GetConstructor(Type, ConstructorInfo) |
Retourne le constructeur du type générique construit spécifié qui correspond au constructeur spécifié de la définition de type générique. |
| GetConstructor(Type[]) |
Recherche un constructeur d’instance publique dont les paramètres correspondent aux types dans le tableau spécifié. (Hérité de Type) |
| GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
En cas de substitution dans une classe dérivée, recherche un constructeur dont les paramètres correspondent aux types et modificateurs d’argument spécifiés, à l’aide des contraintes de liaison spécifiées et de la convention d’appel spécifiée. (Hérité de Type) |
| GetConstructors() |
Retourne tous les constructeurs publics définis pour le Typeactuel. (Hérité de Type) |
| GetConstructors(BindingFlags) |
Retourne un tableau d’objets ConstructorInfo représentant les constructeurs publics et non publics définis pour cette classe, comme spécifié. |
| GetCustomAttributes(Boolean) |
Retourne tous les attributs personnalisés définis pour ce type. |
| GetCustomAttributes(Type, Boolean) |
Retourne tous les attributs personnalisés du type actuel qui sont assignables à un type spécifié. |
| GetCustomAttributesData() |
Retourne une liste d’objets CustomAttributeData représentant des données sur les attributs qui ont été appliqués au membre cible. (Hérité de MemberInfo) |
| GetDeclaredEvent(String) |
Retourne un objet qui représente l’événement spécifié déclaré par le type actuel. (Hérité de TypeInfo) |
| GetDeclaredField(String) |
Retourne un objet qui représente le champ spécifié déclaré par le type actuel. (Hérité de TypeInfo) |
| GetDeclaredMethod(String) |
Retourne un objet qui représente la méthode spécifiée déclarée par le type actuel. (Hérité de TypeInfo) |
| GetDeclaredMethods(String) |
Retourne une collection qui contient toutes les méthodes déclarées sur le type actuel qui correspondent au nom spécifié. (Hérité de TypeInfo) |
| GetDeclaredNestedType(String) |
Retourne un objet qui représente le type imbriqué spécifié déclaré par le type actuel. (Hérité de TypeInfo) |
| GetDeclaredProperty(String) |
Retourne un objet qui représente la propriété spécifiée déclarée par le type actuel. (Hérité de TypeInfo) |
| GetDefaultMembers() |
Recherche les membres définis pour le Type actuel dont la DefaultMemberAttribute est définie. (Hérité de Type) |
| GetElementType() |
L’appel de cette méthode lève NotSupportedExceptiontoujours . |
| GetEnumName(Object) |
Retourne le nom de la constante qui a la valeur spécifiée, pour le type d’énumération actuel. (Hérité de Type) |
| GetEnumNames() |
Retourne les noms des membres du type d’énumération actuel. (Hérité de Type) |
| GetEnumUnderlyingType() |
Retourne le type sous-jacent du type d’énumération actuel. (Hérité de Type) |
| GetEnumValues() |
Retourne un tableau des valeurs des constantes dans le type d’énumération actuel. (Hérité de Type) |
| GetEvent(String, BindingFlags) |
Retourne l’événement avec le nom spécifié. |
| GetEvent(String) |
Retourne l’objet EventInfo représentant l’événement public spécifié. (Hérité de Type) |
| GetEvents() |
Retourne les événements publics déclarés ou hérités par ce type. |
| GetEvents(BindingFlags) |
Retourne les événements publics et non publics déclarés par ce type. |
| GetField(String, BindingFlags) |
Retourne le champ spécifié par le nom donné. |
| GetField(String) |
Recherche le champ public avec le nom spécifié. (Hérité de Type) |
| GetField(Type, FieldInfo) |
Retourne le champ du type générique construit spécifié qui correspond au champ spécifié de la définition de type générique. |
| GetFields() |
Retourne tous les champs publics de la Typeactuelle. (Hérité de Type) |
| GetFields(BindingFlags) |
Retourne les champs publics et non publics déclarés par ce type. |
| GetGenericArguments() |
Retourne un tableau d’objets Type représentant les arguments de type d’un type générique ou les paramètres de type d’une définition de type générique. |
| GetGenericParameterConstraints() |
Retourne un tableau d’objets Type qui représentent les contraintes sur le paramètre de type générique actuel. (Hérité de Type) |
| GetGenericTypeDefinition() |
Retourne un Type objet qui représente une définition de type générique à partir de laquelle le type actuel peut être obtenu. |
| GetHashCode() |
Retourne le code de hachage pour cette instance. (Hérité de Type) |
| GetInterface(String, Boolean) |
Retourne l’interface implémentée (directement ou indirectement) par cette classe avec le nom complet correspondant au nom d’interface donné. |
| GetInterface(String) |
Recherche l’interface avec le nom spécifié. (Hérité de Type) |
| GetInterfaceMap(Type) |
Retourne un mappage d’interface pour l’interface demandée. |
| GetInterfaces() |
Retourne un tableau de toutes les interfaces implémentées sur ce type et ses types de base. |
| GetMember(String, BindingFlags) |
Recherche les membres spécifiés à l’aide des contraintes de liaison spécifiées. (Hérité de Type) |
| GetMember(String, MemberTypes, BindingFlags) |
Retourne tous les membres publics et non publics déclarés ou hérités par ce type, comme spécifié. |
| GetMember(String) |
Recherche les membres publics portant le nom spécifié. (Hérité de Type) |
| GetMembers() |
Retourne tous les membres publics du Typeactuel. (Hérité de Type) |
| GetMembers(BindingFlags) |
Retourne les membres des membres publics et non publics déclarés ou hérités par ce type. |
| GetMethod(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
Recherche la méthode spécifiée dont les paramètres correspondent aux types et modificateurs d’argument spécifiés, à l’aide des contraintes de liaison spécifiées et de la convention d’appel spécifiée. (Hérité de Type) |
| GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[]) |
Recherche la méthode spécifiée dont les paramètres correspondent aux types d’arguments et modificateurs spécifiés, à l’aide des contraintes de liaison spécifiées. (Hérité de Type) |
| GetMethod(String, BindingFlags) |
Recherche la méthode spécifiée à l’aide des contraintes de liaison spécifiées. (Hérité de Type) |
| GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
Recherche la méthode spécifiée dont les paramètres correspondent au nombre de paramètres génériques, aux types d’arguments et aux modificateurs spécifiés, à l’aide des contraintes de liaison spécifiées et de la convention d’appel spécifiée. (Hérité de Type) |
| GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[]) |
Recherche la méthode spécifiée dont les paramètres correspondent au nombre de paramètres génériques, aux types d’arguments et aux modificateurs spécifiés, à l’aide des contraintes de liaison spécifiées. (Hérité de Type) |
| GetMethod(String, Int32, Type[], ParameterModifier[]) |
Recherche la méthode publique spécifiée dont les paramètres correspondent au nombre de paramètres génériques, aux types d’arguments et aux modificateurs spécifiés. (Hérité de Type) |
| GetMethod(String, Int32, Type[]) |
Recherche la méthode publique spécifiée dont les paramètres correspondent au nombre de paramètres et aux types d’arguments génériques spécifiés. (Hérité de Type) |
| GetMethod(String, Type[], ParameterModifier[]) |
Recherche la méthode publique spécifiée dont les paramètres correspondent aux types et modificateurs d’argument spécifiés. (Hérité de Type) |
| GetMethod(String, Type[]) |
Recherche la méthode publique spécifiée dont les paramètres correspondent aux types d’arguments spécifiés. (Hérité de Type) |
| GetMethod(String) |
Recherche la méthode publique avec le nom spécifié. (Hérité de Type) |
| GetMethod(Type, MethodInfo) |
Retourne la méthode du type générique construit spécifié qui correspond à la méthode spécifiée de la définition de type générique. |
| GetMethodImpl(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
En cas de substitution dans une classe dérivée, recherche la méthode spécifiée dont les paramètres correspondent aux types d’arguments et modificateurs spécifiés, à l’aide des contraintes de liaison spécifiées et de la convention d’appel spécifiée. (Hérité de Type) |
| GetMethodImpl(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
En cas de substitution dans une classe dérivée, recherche la méthode spécifiée dont les paramètres correspondent au nombre de paramètres génériques, aux types d’arguments et aux modificateurs spécifiés, à l’aide des contraintes de liaison spécifiées et de la convention d’appel spécifiée. (Hérité de Type) |
| GetMethods() |
Retourne toutes les méthodes publiques du Typeactuel. (Hérité de Type) |
| GetMethods(BindingFlags) |
Retourne toutes les méthodes publiques et non publiques déclarées ou héritées par ce type, comme spécifié. |
| GetNestedType(String, BindingFlags) |
Retourne les types imbriqués publics et non publics déclarés par ce type. |
| GetNestedType(String) |
Recherche le type imbriqué public avec le nom spécifié. (Hérité de Type) |
| GetNestedTypes() |
Retourne les types publics imbriqués dans le Typeactuel. (Hérité de Type) |
| GetNestedTypes(BindingFlags) |
Retourne les types imbriqués publics et non publics déclarés ou hérités par ce type. |
| GetProperties() |
Retourne toutes les propriétés publiques de la Typeactuelle. (Hérité de Type) |
| GetProperties(BindingFlags) |
Retourne toutes les propriétés publiques et non publiques déclarées ou héritées par ce type, comme spécifié. |
| GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) |
Recherche la propriété spécifiée dont les paramètres correspondent aux types d’arguments et modificateurs spécifiés, à l’aide des contraintes de liaison spécifiées. (Hérité de Type) |
| GetProperty(String, BindingFlags) |
Recherche la propriété spécifiée à l’aide des contraintes de liaison spécifiées. (Hérité de Type) |
| GetProperty(String, Type, Type[], ParameterModifier[]) |
Recherche la propriété publique spécifiée dont les paramètres correspondent aux types et modificateurs d’argument spécifiés. (Hérité de Type) |
| GetProperty(String, Type, Type[]) |
Recherche la propriété publique spécifiée dont les paramètres correspondent aux types d’arguments spécifiés. (Hérité de Type) |
| GetProperty(String, Type) |
Recherche la propriété publique avec le nom et le type de retour spécifiés. (Hérité de Type) |
| GetProperty(String, Type[]) |
Recherche la propriété publique spécifiée dont les paramètres correspondent aux types d’arguments spécifiés. (Hérité de Type) |
| GetProperty(String) |
Recherche la propriété publique avec le nom spécifié. (Hérité de Type) |
| GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[]) |
En cas de substitution dans une classe dérivée, recherche la propriété spécifiée dont les paramètres correspondent aux types et modificateurs d’argument spécifiés, à l’aide des contraintes de liaison spécifiées. (Hérité de Type) |
| GetType() |
Obtient le Typeactuel . (Hérité de Type) |
| GetTypeCodeImpl() |
Retourne le code de type sous-jacent de cette instance Type. (Hérité de Type) |
| HasElementTypeImpl() |
En cas de substitution dans une classe dérivée, implémente la propriété HasElementType et détermine si le Type actuel englobe ou fait référence à un autre type ; autrement dit, si le Type actuel est un tableau, un pointeur ou est passé par référence. (Hérité de Type) |
| HasSameMetadataDefinitionAs(MemberInfo) |
Définit et crée de nouvelles instances de classes pendant l’exécution. (Hérité de MemberInfo) |
| InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo) |
Appelle le membre spécifié, en utilisant les contraintes de liaison spécifiées et en correspondant à la liste et à la culture d’arguments spécifiées. (Hérité de Type) |
| InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) |
Appelle le membre spécifié. La méthode à appeler doit être accessible et fournir la correspondance la plus spécifique avec la liste d’arguments spécifiée, sous les contraintes des attributs de classeur et d’appel spécifiés. |
| InvokeMember(String, BindingFlags, Binder, Object, Object[]) |
Appelle le membre spécifié, en utilisant les contraintes de liaison spécifiées et en correspondant à la liste d’arguments spécifiée. (Hérité de Type) |
| IsArrayImpl() |
En cas de substitution dans une classe dérivée, implémente la propriété IsArray et détermine si le Type est un tableau. (Hérité de Type) |
| IsAssignableFrom(Type) |
Obtient une valeur qui indique si un spécifié Type peut être affecté à cet objet. |
| IsAssignableFrom(TypeInfo) |
Obtient une valeur qui indique si un objet spécifié TypeInfo peut être affecté à cet objet. |
| IsByRefImpl() |
En cas de substitution dans une classe dérivée, implémente la propriété IsByRef et détermine si le Type est passé par référence. (Hérité de Type) |
| IsCOMObjectImpl() |
En cas de substitution dans une classe dérivée, implémente la propriété IsCOMObject et détermine si l'Type est un objet COM. (Hérité de Type) |
| IsContextfulImpl() |
Implémente la propriété IsContextful et détermine si la Type peut être hébergée dans un contexte. (Hérité de Type) |
| IsCreated() |
Retourne une valeur qui indique si le type dynamique actuel a été créé. |
| IsDefined(Type, Boolean) |
Détermine si un attribut personnalisé est appliqué au type actuel. |
| IsEnumDefined(Object) |
Retourne une valeur qui indique si la valeur spécifiée existe dans le type d’énumération actuel. (Hérité de Type) |
| IsEquivalentTo(Type) |
Détermine si deux types COM ont la même identité et sont éligibles à l’équivalence de type. (Hérité de Type) |
| IsInstanceOfType(Object) |
Détermine si l’objet spécifié est une instance du Typeactuel . (Hérité de Type) |
| IsMarshalByRefImpl() |
Implémente la propriété IsMarshalByRef et détermine si le Type est marshalé par référence. (Hérité de Type) |
| IsPointerImpl() |
En cas de substitution dans une classe dérivée, implémente la propriété IsPointer et détermine si l'Type est un pointeur. (Hérité de Type) |
| IsPrimitiveImpl() |
En cas de substitution dans une classe dérivée, implémente la propriété IsPrimitive et détermine si l'Type est l’un des types primitifs. (Hérité de Type) |
| IsSubclassOf(Type) |
Détermine si ce type est dérivé d’un type spécifié. |
| IsValueTypeImpl() |
Implémente la propriété IsValueType et détermine si l'Type est un type valeur ; c’est-à-dire qu’il ne s’agit pas d’une classe ou d’une interface. (Hérité de Type) |
| MakeArrayType() |
Renvoie un Type objet qui représente un tableau unidimensionnel du type actuel, avec une limite inférieure de zéro. |
| MakeArrayType(Int32) |
Renvoie un Type objet qui représente un tableau du type actuel, avec le nombre spécifié de dimensions. |
| MakeByRefType() |
Renvoie un objet Type qui représente le type actuel lorsqu’il est passé en tant que paramètre |
| MakeGenericType(Type[]) |
Remplace les éléments d’un tableau de types pour les paramètres de type de la définition de type générique actuelle et retourne le type construit résultant. |
| MakePointerType() |
Retourne un Type objet qui représente le type d’un pointeur non managé vers le type actuel. |
| MemberwiseClone() |
Crée une copie superficielle du Objectactuel. (Hérité de Object) |
| SetCustomAttribute(ConstructorInfo, Byte[]) |
Définit un attribut personnalisé à l’aide d’un objet blob d’attributs personnalisé spécifié. |
| SetCustomAttribute(CustomAttributeBuilder) |
Définissez un attribut personnalisé à l’aide d’un générateur d’attributs personnalisé. |
| SetParent(Type) |
Définit le type de base du type en cours de construction. |
| ToString() |
Retourne le nom du type à l’exclusion de l’espace de noms. |
Implémentations d’interfaces explicites
| Nom | Description |
|---|---|
| _MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch. (Hérité de MemberInfo) |
| _MemberInfo.GetType() |
Obtient un Type objet représentant la MemberInfo classe. (Hérité de MemberInfo) |
| _MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr) |
Récupère les informations de type pour un objet, qui peuvent être utilisées ensuite pour obtenir les informations de type d'une interface. (Hérité de MemberInfo) |
| _MemberInfo.GetTypeInfoCount(UInt32) |
Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1). (Hérité de MemberInfo) |
| _MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fournit l’accès aux propriétés et méthodes exposées par un objet. (Hérité de MemberInfo) |
| _Type.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch. (Hérité de Type) |
| _Type.GetTypeInfo(UInt32, UInt32, IntPtr) |
Récupère les informations de type pour un objet, qui peuvent être utilisées ensuite pour obtenir les informations de type d'une interface. (Hérité de Type) |
| _Type.GetTypeInfoCount(UInt32) |
Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1). (Hérité de Type) |
| _Type.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fournit l’accès aux propriétés et méthodes exposées par un objet. (Hérité de Type) |
| _TypeBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch. |
| _TypeBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) |
Récupère les informations de type pour un objet, qui peuvent être utilisées ensuite pour obtenir les informations de type d'une interface. |
| _TypeBuilder.GetTypeInfoCount(UInt32) |
Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1). |
| _TypeBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fournit l’accès aux propriétés et méthodes exposées par un objet. |
| IReflectableType.GetTypeInfo() |
Retourne une représentation du type actuel en tant qu’objet TypeInfo. (Hérité de TypeInfo) |
Méthodes d’extension
| Nom | Description |
|---|---|
| GetCustomAttribute(MemberInfo, Type, Boolean) |
Récupère un attribut personnalisé d’un type spécifié appliqué à un membre spécifié et inspecte éventuellement les ancêtres de ce membre. |
| GetCustomAttribute(MemberInfo, Type) |
Récupère un attribut personnalisé d’un type spécifié appliqué à un membre spécifié. |
| GetCustomAttribute<T>(MemberInfo, Boolean) |
Récupère un attribut personnalisé d’un type spécifié appliqué à un membre spécifié et inspecte éventuellement les ancêtres de ce membre. |
| GetCustomAttribute<T>(MemberInfo) |
Récupère un attribut personnalisé d’un type spécifié appliqué à un membre spécifié. |
| GetCustomAttributes(MemberInfo, Boolean) |
Récupère une collection d’attributs personnalisés appliqués à un membre spécifié et inspecte éventuellement les ancêtres de ce membre. |
| GetCustomAttributes(MemberInfo, Type, Boolean) |
Récupère une collection d’attributs personnalisés d’un type spécifié qui sont appliqués à un membre spécifié et inspecte éventuellement les ancêtres de ce membre. |
| GetCustomAttributes(MemberInfo, Type) |
Récupère une collection d’attributs personnalisés d’un type spécifié qui sont appliqués à un membre spécifié. |
| GetCustomAttributes(MemberInfo) |
Récupère une collection d’attributs personnalisés appliqués à un membre spécifié. |
| GetCustomAttributes<T>(MemberInfo, Boolean) |
Récupère une collection d’attributs personnalisés d’un type spécifié qui sont appliqués à un membre spécifié et inspecte éventuellement les ancêtres de ce membre. |
| GetCustomAttributes<T>(MemberInfo) |
Récupère une collection d’attributs personnalisés d’un type spécifié qui sont appliqués à un membre spécifié. |
| GetRuntimeEvent(Type, String) |
Récupère un objet qui représente l’événement spécifié. |
| GetRuntimeEvents(Type) |
Récupère une collection qui représente tous les événements définis sur un type spécifié. |
| GetRuntimeField(Type, String) |
Récupère un objet qui représente un champ spécifié. |
| GetRuntimeFields(Type) |
Récupère une collection qui représente tous les champs définis sur un type spécifié. |
| GetRuntimeInterfaceMap(TypeInfo, Type) |
Retourne un mappage d’interface pour le type spécifié et l’interface spécifiée. |
| GetRuntimeMethod(Type, String, Type[]) |
Récupère un objet qui représente une méthode spécifiée. |
| GetRuntimeMethods(Type) |
Récupère une collection qui représente toutes les méthodes définies sur un type spécifié. |
| GetRuntimeProperties(Type) |
Récupère une collection qui représente toutes les propriétés définies sur un type spécifié. |
| GetRuntimeProperty(Type, String) |
Récupère un objet qui représente une propriété spécifiée. |
| GetTypeInfo(Type) |
Retourne la représentation TypeInfo du type spécifié. |
| IsDefined(MemberInfo, Type, Boolean) |
Indique si les attributs personnalisés d’un type spécifié sont appliqués à un membre spécifié et, éventuellement, appliqués à ses ancêtres. |
| IsDefined(MemberInfo, Type) |
Indique si les attributs personnalisés d’un type spécifié sont appliqués à un membre spécifié. |