TypeBuilder Clase

Definición

Define y crea nuevas instancias de clases durante el tiempo de ejecución.

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
Herencia
TypeBuilder
Herencia
Atributos
Implementaciones

Ejemplos

En el ejemplo de código siguiente se muestra cómo definir y usar un ensamblado dinámico. El ensamblado de ejemplo contiene un tipo, MyDynamicType, que tiene un campo privado, una propiedad que obtiene y establece el campo privado, constructores que inicializan el campo privado y un método que multiplica un número proporcionado por el usuario por el valor del campo privado y devuelve el resultado.

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

En el ejemplo de código siguiente se muestra cómo compilar un tipo dinámicamente mediante TypeBuilder.

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

Comentarios

Para obtener más información sobre esta API, consulte Comentarios complementarios de API para TypeBuilder.

Campos

Nombre Description
UnspecifiedTypeSize

Representa que no se especifica el tamaño total del tipo.

Propiedades

Nombre Description
Assembly

Recupera el ensamblado dinámico que contiene esta definición de tipo.

AssemblyQualifiedName

Devuelve el nombre completo de este tipo calificado por el nombre para mostrar del ensamblado.

Attributes

Obtiene los atributos asociados a .Type

(Heredado de Type)
BaseType

Recupera el tipo base de este tipo.

ContainsGenericParameters

Obtiene un valor que indica si el objeto actual Type tiene parámetros de tipo que no se han reemplazado por tipos específicos.

(Heredado de Type)
CustomAttributes

Obtiene una colección que contiene los atributos personalizados de este miembro.

(Heredado de MemberInfo)
DeclaredConstructors

Obtiene una colección de los constructores declarados por el tipo actual.

(Heredado de TypeInfo)
DeclaredEvents

Obtiene una colección de los eventos definidos por el tipo actual.

(Heredado de TypeInfo)
DeclaredFields

Obtiene una colección de los campos definidos por el tipo actual.

(Heredado de TypeInfo)
DeclaredMembers

Obtiene una colección de los miembros definidos por el tipo actual.

(Heredado de TypeInfo)
DeclaredMethods

Obtiene una colección de los métodos definidos por el tipo actual.

(Heredado de TypeInfo)
DeclaredNestedTypes

Obtiene una colección de los tipos anidados definidos por el tipo actual.

(Heredado de TypeInfo)
DeclaredProperties

Obtiene una colección de las propiedades definidas por el tipo actual.

(Heredado de TypeInfo)
DeclaringMethod

Obtiene el método que declaró el parámetro de tipo genérico actual.

DeclaringType

Devuelve el tipo que declaró este tipo.

FullName

Recupera la ruta de acceso completa de este tipo.

GenericParameterAttributes

Obtiene un valor que indica la covarianza y las restricciones especiales del parámetro de tipo genérico actual.

GenericParameterPosition

Obtiene la posición de un parámetro de tipo en la lista de parámetros de tipo del tipo genérico que declaró el parámetro.

GenericTypeArguments

Obtiene una matriz de los argumentos de tipo genérico para este tipo.

(Heredado de Type)
GenericTypeParameters

Obtiene una matriz de los parámetros de tipo genérico de la instancia actual.

(Heredado de TypeInfo)
GUID

Recupera el GUID de este tipo.

HasElementType

Obtiene un valor que indica si el actual Type abarca o hace referencia a otro tipo; es decir, si el objeto actual Type es una matriz, un puntero o se pasa por referencia.

(Heredado de Type)
ImplementedInterfaces

Obtiene una colección de las interfaces implementadas por el tipo actual.

(Heredado de TypeInfo)
IsAbstract

Obtiene un valor que indica si es Type abstracto y se debe invalidar.

(Heredado de Type)
IsAnsiClass

Obtiene un valor que indica si el atributo AnsiClass de formato de cadena está seleccionado para .Type

(Heredado de Type)
IsArray

Obtiene un valor que indica si el tipo es una matriz.

(Heredado de Type)
IsAutoClass

Obtiene un valor que indica si el atributo AutoClass de formato de cadena está seleccionado para .Type

(Heredado de Type)
IsAutoLayout

Obtiene un valor que indica si los campos del tipo actual están dispuestos automáticamente por Common Language Runtime.

(Heredado de Type)
IsByRef

Obtiene un valor que indica si Type se pasa por referencia.

(Heredado de Type)
IsByRefLike

Obtiene un valor que indica si el tipo es una estructura similar a byref.

IsClass

Obtiene un valor que indica si Type es una clase o un delegado; es decir, no un tipo de valor o una interfaz.

(Heredado de Type)
IsCOMObject

Obtiene un valor que indica si Type es un objeto COM.

(Heredado de Type)
IsConstructedGenericType

Obtiene un valor que indica si este objeto representa un tipo genérico construido.

IsContextful

Obtiene un valor que indica si Type se puede hospedar en un contexto.

(Heredado de Type)
IsEnum

Obtiene un valor que indica si el objeto actual Type representa una enumeración.

(Heredado de Type)
IsExplicitLayout

Obtiene un valor que indica si los campos del tipo actual se establecen en desplazamientos especificados explícitamente.

(Heredado de Type)
IsGenericMethodParameter

Obtiene un valor que indica si el objeto actual Type representa un parámetro de tipo en la definición de un método genérico.

(Heredado de Type)
IsGenericParameter

Obtiene un valor que indica si el tipo actual es un parámetro de tipo genérico.

IsGenericType

Obtiene un valor que indica si el tipo actual es un tipo genérico.

IsGenericTypeDefinition

Obtiene un valor que indica si el objeto actual TypeBuilder representa una definición de tipo genérico a partir de la cual se pueden construir otros tipos genéricos.

IsGenericTypeParameter

Obtiene un valor que indica si el objeto actual Type representa un parámetro de tipo en la definición de un tipo genérico.

(Heredado de Type)
IsImport

Obtiene un valor que indica si Type tiene aplicado un ComImportAttribute atributo, lo que indica que se importó desde una biblioteca de tipos COM.

(Heredado de Type)
IsInterface

Obtiene un valor que indica si Type es una interfaz; es decir, no una clase o un tipo de valor.

(Heredado de Type)
IsLayoutSequential

Obtiene un valor que indica si los campos del tipo actual se establecen secuencialmente, en el orden en que se definieron o emitieron a los metadatos.

(Heredado de Type)
IsMarshalByRef

Obtiene un valor que indica si Type se serializa por referencia.

(Heredado de Type)
IsNested

Obtiene un valor que indica si el objeto actual Type representa un tipo cuya definición está anidada dentro de la definición de otro tipo.

(Heredado de Type)
IsNestedAssembly

Obtiene un valor que indica si está Type anidado y visible solo dentro de su propio ensamblado.

(Heredado de Type)
IsNestedFamANDAssem

Obtiene un valor que indica si Type está anidado y solo es visible para las clases que pertenecen a su propia familia y a su propio ensamblado.

(Heredado de Type)
IsNestedFamily

Obtiene un valor que indica si está Type anidado y visible solo dentro de su propia familia.

(Heredado de Type)
IsNestedFamORAssem

Obtiene un valor que indica si está Type anidado y solo es visible para las clases que pertenecen a su propia familia o a su propio ensamblado.

(Heredado de Type)
IsNestedPrivate

Obtiene un valor que indica si Type está anidado y declarado privado.

(Heredado de Type)
IsNestedPublic

Obtiene un valor que indica si una clase está anidada y se declara pública.

(Heredado de Type)
IsNotPublic

Obtiene un valor que indica si Type no se declara público.

(Heredado de Type)
IsPointer

Obtiene un valor que indica si Type es un puntero.

(Heredado de Type)
IsPrimitive

Obtiene un valor que indica si Type es uno de los tipos primitivos.

(Heredado de Type)
IsPublic

Obtiene un valor que indica si Type se declara public.

(Heredado de Type)
IsSealed

Obtiene un valor que indica si Type se declara sealed.

(Heredado de Type)
IsSecurityCritical

Obtiene un valor que indica si el tipo actual es crítico para la seguridad o crítico para la seguridad y, por tanto, puede realizar operaciones críticas.

IsSecuritySafeCritical

Obtiene un valor que indica si el tipo actual es crítico para la seguridad; es decir, si puede realizar operaciones críticas y se puede acceder a ellas mediante código transparente.

IsSecurityTransparent

Obtiene un valor que indica si el tipo actual es transparente y, por tanto, no puede realizar operaciones críticas.

IsSerializable

Obtiene un valor que indica si es Type serializable binario.

(Heredado de Type)
IsSignatureType

Obtiene un valor que indica si el tipo es un tipo de firma.

(Heredado de Type)
IsSpecialName

Obtiene un valor que indica si el tipo tiene un nombre que requiere un control especial.

(Heredado de Type)
IsSZArray

Define y crea nuevas instancias de clases durante el tiempo de ejecución.

IsTypeDefinition

Define y crea nuevas instancias de clases durante el tiempo de ejecución.

IsUnicodeClass

Obtiene un valor que indica si el atributo UnicodeClass de formato de cadena está seleccionado para .Type

(Heredado de Type)
IsValueType

Obtiene un valor que indica si Type es un tipo de valor.

(Heredado de Type)
IsVariableBoundArray

Define y crea nuevas instancias de clases durante el tiempo de ejecución.

IsVisible

Obtiene un valor que indica si Type el código puede tener acceso a él fuera del ensamblado.

(Heredado de Type)
MemberType

Obtiene un MemberTypes valor que indica que este miembro es un tipo o un tipo anidado.

(Heredado de Type)
MetadataToken

Obtiene un valor que identifica un elemento de metadatos.

(Heredado de MemberInfo)
Module

Recupera el módulo dinámico que contiene esta definición de tipo.

Name

Recupera el nombre de este tipo.

Namespace

Recupera el espacio de nombres donde se define.TypeBuilder

PackingSize

Recupera el tamaño de empaquetado de este tipo.

ReflectedType

Devuelve el tipo que se usó para obtener este tipo.

Size

Recupera el tamaño total de un tipo.

StructLayoutAttribute

Obtiene un StructLayoutAttribute objeto que describe el diseño del tipo actual.

(Heredado de Type)
TypeHandle

No se admite en módulos dinámicos.

TypeInitializer

Obtiene el inicializador para el tipo.

(Heredado de Type)
TypeToken

Devuelve el token de tipo de este tipo.

UnderlyingSystemType

Devuelve el tipo de sistema subyacente para este TypeBuilder.

Métodos

Nombre Description
AddDeclarativeSecurity(SecurityAction, PermissionSet)

Agrega seguridad declarativa a este tipo.

AddInterfaceImplementation(Type)

Agrega una interfaz que este tipo implementa.

AsType()

Devuelve el tipo actual como un Type objeto .

(Heredado de TypeInfo)
CreateType()

Crea un Type objeto para la clase . Después de definir campos y métodos en la clase , CreateType se llama a para cargar su Type objeto.

CreateTypeInfo()

Obtiene un TypeInfo objeto que representa este tipo.

DefineConstructor(MethodAttributes, CallingConventions, Type[], Type[][], Type[][])

Agrega un nuevo constructor al tipo, con los atributos, la firma y los modificadores personalizados especificados.

DefineConstructor(MethodAttributes, CallingConventions, Type[])

Agrega un nuevo constructor al tipo, con los atributos y la firma especificados.

DefineDefaultConstructor(MethodAttributes)

Define el constructor sin parámetros. El constructor definido aquí simplemente llamará al constructor sin parámetros del elemento primario.

DefineEvent(String, EventAttributes, Type)

Agrega un nuevo evento al tipo, con el nombre, los atributos y el tipo de evento especificados.

DefineField(String, Type, FieldAttributes)

Agrega un nuevo campo al tipo, con el nombre, los atributos y el tipo de campo especificados.

DefineField(String, Type, Type[], Type[], FieldAttributes)

Agrega un nuevo campo al tipo, con el nombre, los atributos, el tipo de campo y los modificadores personalizados especificados.

DefineGenericParameters(String[])

Define los parámetros de tipo genérico para el tipo actual, especificando su número y sus nombres, y devuelve una matriz de GenericTypeParameterBuilder objetos que se pueden usar para establecer sus restricciones.

DefineInitializedData(String, Byte[], FieldAttributes)

Define el campo de datos inicializado en la sección .sdata del archivo ejecutable portátil (PE).

DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][])

Agrega un nuevo método al tipo, con el nombre especificado, los atributos de método, la convención de llamada, la firma del método y los modificadores personalizados especificados.

DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[])

Agrega un nuevo método al tipo, con el nombre especificado, los atributos del método, la convención de llamada y la firma del método.

DefineMethod(String, MethodAttributes, CallingConventions)

Agrega un nuevo método al tipo, con el nombre especificado, los atributos de método y la convención de llamada.

DefineMethod(String, MethodAttributes, Type, Type[])

Agrega un nuevo método al tipo, con el nombre, los atributos de método y la firma de método especificados.

DefineMethod(String, MethodAttributes)

Agrega un nuevo método al tipo, con el nombre y los atributos de método especificados.

DefineMethodOverride(MethodInfo, MethodInfo)

Especifica un cuerpo de método determinado que implementa una declaración de método determinada, potencialmente con un nombre diferente.

DefineNestedType(String, TypeAttributes, Type, Int32)

Define un tipo anidado, dado su nombre, atributos, el tamaño total del tipo y el tipo que extiende.

DefineNestedType(String, TypeAttributes, Type, PackingSize, Int32)

Define un tipo anidado, dado su nombre, atributos, tamaño y el tipo que extiende.

DefineNestedType(String, TypeAttributes, Type, PackingSize)

Define un tipo anidado, dado su nombre, atributos, el tipo que extiende y el tamaño de empaquetado.

DefineNestedType(String, TypeAttributes, Type, Type[])

Define un tipo anidado, dado su nombre, atributos, el tipo que extiende y las interfaces que implementa.

DefineNestedType(String, TypeAttributes, Type)

Define un tipo anidado, dado su nombre, atributos y el tipo que extiende.

DefineNestedType(String, TypeAttributes)

Define un tipo anidado, dado su nombre y atributos.

DefineNestedType(String)

Define un tipo anidado, dado su nombre.

DefinePInvokeMethod(String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)

Define un PInvoke método dado su nombre, el nombre del archivo DLL en el que se define el método, los atributos del método, la convención de llamada del método, el tipo de valor devuelto del método, los tipos de los parámetros del método y las PInvoke marcas.

DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], CallingConvention, CharSet)

Define un PInvoke método dado su nombre, el nombre del archivo DLL en el que se define el método, el nombre del punto de entrada, los atributos del método, la convención de llamada del método, el tipo devuelto del método, los tipos de los parámetros del método y las PInvoke marcas.

DefinePInvokeMethod(String, String, String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][], CallingConvention, CharSet)

Define un PInvoke método dado su nombre, el nombre del archivo DLL en el que se define el método, el nombre del punto de entrada, los atributos del método, la convención de llamada del método, el tipo devuelto del método, los tipos de los parámetros del método, las PInvoke marcas y modificadores personalizados para los parámetros y el tipo de valor devuelto.

DefineProperty(String, PropertyAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][])

Agrega una nueva propiedad al tipo, con el nombre especificado, la convención de llamada, la firma de propiedad y los modificadores personalizados.

DefineProperty(String, PropertyAttributes, CallingConventions, Type, Type[])

Agrega una nueva propiedad al tipo, con el nombre, los atributos, la convención de llamada y la firma de propiedad especificados.

DefineProperty(String, PropertyAttributes, Type, Type[], Type[], Type[], Type[][], Type[][])

Agrega una nueva propiedad al tipo, con el nombre especificado, la firma de propiedad y los modificadores personalizados.

DefineProperty(String, PropertyAttributes, Type, Type[])

Agrega una nueva propiedad al tipo, con el nombre y la firma de propiedad especificados.

DefineTypeInitializer()

Define el inicializador para este tipo.

DefineUninitializedData(String, Int32, FieldAttributes)

Define un campo de datos sin inicializar en la .sdata sección del archivo ejecutable portátil (PE).

Equals(Object)

Determina si el tipo de sistema subyacente del objeto actual Type es el mismo que el tipo de sistema subyacente del especificado Object.

(Heredado de Type)
Equals(Type)

Determina si el tipo de sistema subyacente del actual Type es el mismo que el tipo de sistema subyacente del especificado Type.

(Heredado de Type)
FindInterfaces(TypeFilter, Object)

Devuelve una matriz de objetos que Type representa una lista filtrada de interfaces implementadas o heredadas por el objeto actual Type.

(Heredado de Type)
FindMembers(MemberTypes, BindingFlags, MemberFilter, Object)

Devuelve una matriz filtrada de MemberInfo objetos del tipo de miembro especificado.

(Heredado de Type)
GetArrayRank()

Obtiene el número de dimensiones de una matriz.

(Heredado de Type)
GetAttributeFlagsImpl()

Cuando se reemplaza en una clase derivada, implementa la Attributes propiedad y obtiene una combinación bit a bit de valores de enumeración que indican los atributos asociados a Type.

(Heredado de Type)
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Busca un constructor cuyos parámetros coincidan con los tipos y modificadores de argumento especificados, utilizando las restricciones de enlace especificadas y la convención de llamada especificada.

(Heredado de Type)
GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[])

Busca un constructor cuyos parámetros coincidan con los tipos de argumento y modificadores especificados, utilizando las restricciones de enlace especificadas.

(Heredado de Type)
GetConstructor(Type, ConstructorInfo)

Devuelve el constructor del tipo genérico construido especificado que corresponde al constructor especificado de la definición de tipo genérico.

GetConstructor(Type[])

Busca un constructor de instancia pública cuyos parámetros coincidan con los tipos de la matriz especificada.

(Heredado de Type)
GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Cuando se reemplaza en una clase derivada, busca un constructor cuyos parámetros coincidan con los tipos y modificadores de argumento especificados, utilizando las restricciones de enlace especificadas y la convención de llamada especificada.

(Heredado de Type)
GetConstructors()

Devuelve todos los constructores públicos definidos para el objeto actual Type.

(Heredado de Type)
GetConstructors(BindingFlags)

Devuelve una matriz de ConstructorInfo objetos que representan los constructores públicos y no públicos definidos para esta clase, tal como se especifica.

GetCustomAttributes(Boolean)

Devuelve todos los atributos personalizados definidos para este tipo.

GetCustomAttributes(Type, Boolean)

Devuelve todos los atributos personalizados del tipo actual que se pueden asignar a un tipo especificado.

GetCustomAttributesData()

Devuelve una lista de CustomAttributeData objetos que representan datos sobre los atributos que se han aplicado al miembro de destino.

(Heredado de MemberInfo)
GetDeclaredEvent(String)

Devuelve un objeto que representa el evento especificado declarado por el tipo actual.

(Heredado de TypeInfo)
GetDeclaredField(String)

Devuelve un objeto que representa el campo especificado declarado por el tipo actual.

(Heredado de TypeInfo)
GetDeclaredMethod(String)

Devuelve un objeto que representa el método especificado declarado por el tipo actual.

(Heredado de TypeInfo)
GetDeclaredMethods(String)

Devuelve una colección que contiene todos los métodos declarados en el tipo actual que coinciden con el nombre especificado.

(Heredado de TypeInfo)
GetDeclaredNestedType(String)

Devuelve un objeto que representa el tipo anidado especificado declarado por el tipo actual.

(Heredado de TypeInfo)
GetDeclaredProperty(String)

Devuelve un objeto que representa la propiedad especificada declarada por el tipo actual.

(Heredado de TypeInfo)
GetDefaultMembers()

Busca los miembros definidos para el actual Type cuyo DefaultMemberAttribute conjunto está establecido.

(Heredado de Type)
GetElementType()

Al llamar a este método siempre se produce NotSupportedException.

GetEnumName(Object)

Devuelve el nombre de la constante que tiene el valor especificado, para el tipo de enumeración actual.

(Heredado de Type)
GetEnumNames()

Devuelve los nombres de los miembros del tipo de enumeración actual.

(Heredado de Type)
GetEnumUnderlyingType()

Devuelve el tipo subyacente del tipo de enumeración actual.

(Heredado de Type)
GetEnumValues()

Devuelve una matriz de los valores de las constantes del tipo de enumeración actual.

(Heredado de Type)
GetEvent(String, BindingFlags)

Devuelve el evento con el nombre especificado.

GetEvent(String)

Devuelve el EventInfo objeto que representa el evento público especificado.

(Heredado de Type)
GetEvents()

Devuelve los eventos públicos declarados o heredados por este tipo.

GetEvents(BindingFlags)

Devuelve los eventos públicos y no públicos declarados por este tipo.

GetField(String, BindingFlags)

Devuelve el campo especificado por el nombre especificado.

GetField(String)

Busca el campo público con el nombre especificado.

(Heredado de Type)
GetField(Type, FieldInfo)

Devuelve el campo del tipo genérico construido especificado que corresponde al campo especificado de la definición de tipo genérico.

GetFields()

Devuelve todos los campos públicos del objeto actual Type.

(Heredado de Type)
GetFields(BindingFlags)

Devuelve los campos públicos y no públicos declarados por este tipo.

GetGenericArguments()

Devuelve una matriz de Type objetos que representa los argumentos de tipo de un tipo genérico o los parámetros de tipo de una definición de tipo genérico.

GetGenericParameterConstraints()

Devuelve una matriz de Type objetos que representan las restricciones en el parámetro de tipo genérico actual.

(Heredado de Type)
GetGenericTypeDefinition()

Devuelve un Type objeto que representa una definición de tipo genérico a partir de la cual se puede obtener el tipo actual.

GetHashCode()

Devuelve el código hash de esta instancia.

(Heredado de Type)
GetInterface(String, Boolean)

Devuelve la interfaz implementada (directa o indirectamente) por esta clase con el nombre completo que coincide con el nombre de interfaz especificado.

GetInterface(String)

Busca la interfaz con el nombre especificado.

(Heredado de Type)
GetInterfaceMap(Type)

Devuelve una asignación de interfaz para la interfaz solicitada.

GetInterfaces()

Devuelve una matriz de todas las interfaces implementadas en este tipo y sus tipos base.

GetMember(String, BindingFlags)

Busca los miembros especificados mediante las restricciones de enlace especificadas.

(Heredado de Type)
GetMember(String, MemberTypes, BindingFlags)

Devuelve todos los miembros públicos y no públicos declarados o heredados por este tipo, tal como se especifica.

GetMember(String)

Busca los miembros públicos con el nombre especificado.

(Heredado de Type)
GetMembers()

Devuelve todos los miembros públicos del objeto actual Type.

(Heredado de Type)
GetMembers(BindingFlags)

Devuelve los miembros de los miembros públicos y no públicos declarados o heredados por este tipo.

GetMethod(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Busca el método especificado cuyos parámetros coinciden con los tipos y modificadores de argumento especificados, utilizando las restricciones de enlace especificadas y la convención de llamada especificada.

(Heredado de Type)
GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[])

Busca el método especificado cuyos parámetros coinciden con los tipos de argumento y modificadores especificados, utilizando las restricciones de enlace especificadas.

(Heredado de Type)
GetMethod(String, BindingFlags)

Busca el método especificado mediante las restricciones de enlace especificadas.

(Heredado de Type)
GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Busca el método especificado cuyos parámetros coinciden con el recuento de parámetros genéricos, los tipos de argumento y los modificadores especificados, utilizando las restricciones de enlace especificadas y la convención de llamada especificada.

(Heredado de Type)
GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[])

Busca el método especificado cuyos parámetros coinciden con el recuento de parámetros genéricos, los tipos de argumento y los modificadores especificados mediante las restricciones de enlace especificadas.

(Heredado de Type)
GetMethod(String, Int32, Type[], ParameterModifier[])

Busca el método público especificado cuyos parámetros coinciden con el recuento de parámetros genéricos, los tipos de argumento y los modificadores especificados.

(Heredado de Type)
GetMethod(String, Int32, Type[])

Busca el método público especificado cuyos parámetros coinciden con el número de parámetros genéricos y los tipos de argumento especificados.

(Heredado de Type)
GetMethod(String, Type[], ParameterModifier[])

Busca el método público especificado cuyos parámetros coinciden con los tipos de argumento y modificadores especificados.

(Heredado de Type)
GetMethod(String, Type[])

Busca el método público especificado cuyos parámetros coinciden con los tipos de argumento especificados.

(Heredado de Type)
GetMethod(String)

Busca el método público con el nombre especificado.

(Heredado de Type)
GetMethod(Type, MethodInfo)

Devuelve el método del tipo genérico construido especificado que corresponde al método especificado de la definición de tipo genérico.

GetMethodImpl(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Cuando se reemplaza en una clase derivada, busca el método especificado cuyos parámetros coinciden con los tipos y modificadores de argumento especificados, utilizando las restricciones de enlace especificadas y la convención de llamada especificada.

(Heredado de Type)
GetMethodImpl(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Cuando se reemplaza en una clase derivada, busca el método especificado cuyos parámetros coinciden con el recuento de parámetros genéricos, los tipos de argumento y los modificadores especificados, utilizando las restricciones de enlace especificadas y la convención de llamada especificada.

(Heredado de Type)
GetMethods()

Devuelve todos los métodos públicos del objeto actual Type.

(Heredado de Type)
GetMethods(BindingFlags)

Devuelve todos los métodos públicos y no públicos declarados o heredados por este tipo, tal como se especifica.

GetNestedType(String, BindingFlags)

Devuelve los tipos anidados públicos y no públicos declarados por este tipo.

GetNestedType(String)

Busca el tipo anidado público con el nombre especificado.

(Heredado de Type)
GetNestedTypes()

Devuelve los tipos públicos anidados en el objeto actual Type.

(Heredado de Type)
GetNestedTypes(BindingFlags)

Devuelve los tipos anidados públicos y no públicos declarados o heredados por este tipo.

GetProperties()

Devuelve todas las propiedades públicas del objeto actual Type.

(Heredado de Type)
GetProperties(BindingFlags)

Devuelve todas las propiedades públicas y no públicas declaradas o heredadas por este tipo, tal como se especifica.

GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

Busca la propiedad especificada cuyos parámetros coinciden con los tipos de argumento y modificadores especificados, utilizando las restricciones de enlace especificadas.

(Heredado de Type)
GetProperty(String, BindingFlags)

Busca la propiedad especificada mediante las restricciones de enlace especificadas.

(Heredado de Type)
GetProperty(String, Type, Type[], ParameterModifier[])

Busca la propiedad pública especificada cuyos parámetros coinciden con los tipos de argumento y modificadores especificados.

(Heredado de Type)
GetProperty(String, Type, Type[])

Busca la propiedad pública especificada cuyos parámetros coinciden con los tipos de argumento especificados.

(Heredado de Type)
GetProperty(String, Type)

Busca la propiedad pública con el nombre y el tipo de valor devuelto especificados.

(Heredado de Type)
GetProperty(String, Type[])

Busca la propiedad pública especificada cuyos parámetros coinciden con los tipos de argumento especificados.

(Heredado de Type)
GetProperty(String)

Busca la propiedad pública con el nombre especificado.

(Heredado de Type)
GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

Cuando se reemplaza en una clase derivada, busca la propiedad especificada cuyos parámetros coinciden con los tipos y modificadores de argumento especificados, utilizando las restricciones de enlace especificadas.

(Heredado de Type)
GetType()

Obtiene el objeto actual Type.

(Heredado de Type)
GetTypeCodeImpl()

Devuelve el código de tipo subyacente de esta Type instancia.

(Heredado de Type)
HasElementTypeImpl()

Cuando se reemplaza en una clase derivada, implementa la HasElementType propiedad y determina si el actual Type abarca o hace referencia a otro tipo; es decir, si el objeto actual Type es una matriz, un puntero o se pasa por referencia.

(Heredado de Type)
HasSameMetadataDefinitionAs(MemberInfo)

Define y crea nuevas instancias de clases durante el tiempo de ejecución.

(Heredado de MemberInfo)
InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo)

Invoca al miembro especificado mediante las restricciones de enlace especificadas y coincide con la lista de argumentos y la referencia cultural especificadas.

(Heredado de Type)
InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])

Invoca al miembro especificado. El método que se va a invocar debe ser accesible y proporcionar la coincidencia más específica con la lista de argumentos especificada, bajo las restricciones del enlazador y los atributos de invocación especificados.

InvokeMember(String, BindingFlags, Binder, Object, Object[])

Invoca al miembro especificado mediante las restricciones de enlace especificadas y coincide con la lista de argumentos especificada.

(Heredado de Type)
IsArrayImpl()

Cuando se invalida en una clase derivada, implementa la IsArray propiedad y determina si es Type una matriz.

(Heredado de Type)
IsAssignableFrom(Type)

Obtiene un valor que indica si se puede asignar un objeto especificado Type a este objeto.

IsAssignableFrom(TypeInfo)

Obtiene un valor que indica si se puede asignar un objeto especificado TypeInfo a este objeto.

IsByRefImpl()

Cuando se invalida en una clase derivada, implementa la IsByRef propiedad y determina si Type se pasa por referencia.

(Heredado de Type)
IsCOMObjectImpl()

Cuando se reemplaza en una clase derivada, implementa la IsCOMObject propiedad y determina si Type es un objeto COM.

(Heredado de Type)
IsContextfulImpl()

Implementa la IsContextful propiedad y determina si Type se puede hospedar en un contexto.

(Heredado de Type)
IsCreated()

Devuelve un valor que indica si se ha creado el tipo dinámico actual.

IsDefined(Type, Boolean)

Determina si se aplica un atributo personalizado al tipo actual.

IsEnumDefined(Object)

Devuelve un valor que indica si el valor especificado existe en el tipo de enumeración actual.

(Heredado de Type)
IsEquivalentTo(Type)

Determina si dos tipos COM tienen la misma identidad y son aptas para la equivalencia de tipos.

(Heredado de Type)
IsInstanceOfType(Object)

Determina si el objeto especificado es una instancia del objeto actual Type.

(Heredado de Type)
IsMarshalByRefImpl()

Implementa la IsMarshalByRef propiedad y determina si se Type serializa por referencia.

(Heredado de Type)
IsPointerImpl()

Cuando se invalida en una clase derivada, implementa la IsPointer propiedad y determina si Type es un puntero.

(Heredado de Type)
IsPrimitiveImpl()

Cuando se reemplaza en una clase derivada, implementa la IsPrimitive propiedad y determina si Type es uno de los tipos primitivos.

(Heredado de Type)
IsSubclassOf(Type)

Determina si este tipo se deriva de un tipo especificado.

IsValueTypeImpl()

Implementa la IsValueType propiedad y determina si Type es un tipo de valor; es decir, no una clase o una interfaz.

(Heredado de Type)
MakeArrayType()

Devuelve un Type objeto que representa una matriz unidimensional del tipo actual, con un límite inferior de cero.

MakeArrayType(Int32)

Devuelve un Type objeto que representa una matriz del tipo actual, con el número especificado de dimensiones.

MakeByRefType()

Devuelve un objeto que representa el tipo actual cuando se pasa como parámetro /> en Visual Basic).

MakeGenericType(Type[])

Sustituye los elementos de una matriz de tipos para los parámetros de tipo de la definición de tipo genérico actual y devuelve el tipo construido resultante.

MakePointerType()

Devuelve un Type objeto que representa el tipo de un puntero no administrado al tipo actual.

MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
SetCustomAttribute(ConstructorInfo, Byte[])

Establece un atributo personalizado mediante un blob de atributo personalizado especificado.

SetCustomAttribute(CustomAttributeBuilder)

Establezca un atributo personalizado mediante un generador de atributos personalizados.

SetParent(Type)

Establece el tipo base del tipo actualmente en construcción.

ToString()

Devuelve el nombre del tipo que excluye el espacio de nombres.

Implementaciones de interfaz explícitas

Nombre Description
_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.

(Heredado de MemberInfo)
_MemberInfo.GetType()

Obtiene un Type objeto que representa la MemberInfo clase .

(Heredado de MemberInfo)
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera la información de tipo de un objeto, que se puede usar después para obtener la información de tipo de una interfaz.

(Heredado de MemberInfo)
_MemberInfo.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).

(Heredado de MemberInfo)
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a propiedades y métodos expuestos por un objeto .

(Heredado de MemberInfo)
_Type.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.

(Heredado de Type)
_Type.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera la información de tipo de un objeto, que se puede usar después para obtener la información de tipo de una interfaz.

(Heredado de Type)
_Type.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).

(Heredado de Type)
_Type.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a propiedades y métodos expuestos por un objeto .

(Heredado de Type)
_TypeBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.

_TypeBuilder.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera la información de tipo de un objeto, que se puede usar después para obtener la información de tipo de una interfaz.

_TypeBuilder.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).

_TypeBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a propiedades y métodos expuestos por un objeto .

IReflectableType.GetTypeInfo()

Devuelve una representación del tipo actual como un TypeInfo objeto .

(Heredado de TypeInfo)

Métodos de extensión

Nombre Description
GetCustomAttribute(MemberInfo, Type, Boolean)

Recupera un atributo personalizado de un tipo especificado que se aplica a un miembro especificado y, opcionalmente, inspecciona los antecesores de ese miembro.

GetCustomAttribute(MemberInfo, Type)

Recupera un atributo personalizado de un tipo especificado que se aplica a un miembro especificado.

GetCustomAttribute<T>(MemberInfo, Boolean)

Recupera un atributo personalizado de un tipo especificado que se aplica a un miembro especificado y, opcionalmente, inspecciona los antecesores de ese miembro.

GetCustomAttribute<T>(MemberInfo)

Recupera un atributo personalizado de un tipo especificado que se aplica a un miembro especificado.

GetCustomAttributes(MemberInfo, Boolean)

Recupera una colección de atributos personalizados que se aplican a un miembro especificado y, opcionalmente, inspecciona los antecesores de ese miembro.

GetCustomAttributes(MemberInfo, Type, Boolean)

Recupera una colección de atributos personalizados de un tipo especificado que se aplica a un miembro especificado y, opcionalmente, inspecciona los antecesores de ese miembro.

GetCustomAttributes(MemberInfo, Type)

Recupera una colección de atributos personalizados de un tipo especificado que se aplica a un miembro especificado.

GetCustomAttributes(MemberInfo)

Recupera una colección de atributos personalizados que se aplican a un miembro especificado.

GetCustomAttributes<T>(MemberInfo, Boolean)

Recupera una colección de atributos personalizados de un tipo especificado que se aplica a un miembro especificado y, opcionalmente, inspecciona los antecesores de ese miembro.

GetCustomAttributes<T>(MemberInfo)

Recupera una colección de atributos personalizados de un tipo especificado que se aplica a un miembro especificado.

GetRuntimeEvent(Type, String)

Recupera un objeto que representa el evento especificado.

GetRuntimeEvents(Type)

Recupera una colección que representa todos los eventos definidos en un tipo especificado.

GetRuntimeField(Type, String)

Recupera un objeto que representa un campo especificado.

GetRuntimeFields(Type)

Recupera una colección que representa todos los campos definidos en un tipo especificado.

GetRuntimeInterfaceMap(TypeInfo, Type)

Devuelve una asignación de interfaz para el tipo especificado y la interfaz especificada.

GetRuntimeMethod(Type, String, Type[])

Recupera un objeto que representa un método especificado.

GetRuntimeMethods(Type)

Recupera una colección que representa todos los métodos definidos en un tipo especificado.

GetRuntimeProperties(Type)

Recupera una colección que representa todas las propiedades definidas en un tipo especificado.

GetRuntimeProperty(Type, String)

Recupera un objeto que representa una propiedad especificada.

GetTypeInfo(Type)

Devuelve la TypeInfo representación del tipo especificado.

IsDefined(MemberInfo, Type, Boolean)

Indica si los atributos personalizados de un tipo especificado se aplican a un miembro especificado y, opcionalmente, se aplican a sus antecesores.

IsDefined(MemberInfo, Type)

Indica si los atributos personalizados de un tipo especificado se aplican a un miembro especificado.

Se aplica a

Consulte también