ModuleBuilder.DefineEnum(String, TypeAttributes, Type) Método

Definición

Define un tipo de enumeración que consiste en un tipo de valor con un único campo no estático denominado value__ del tipo especificado.

public:
 System::Reflection::Emit::EnumBuilder ^ DefineEnum(System::String ^ name, System::Reflection::TypeAttributes visibility, Type ^ underlyingType);
public System.Reflection.Emit.EnumBuilder DefineEnum (string name, System.Reflection.TypeAttributes visibility, Type underlyingType);
member this.DefineEnum : string * System.Reflection.TypeAttributes * Type -> System.Reflection.Emit.EnumBuilder
Public Function DefineEnum (name As String, visibility As TypeAttributes, underlyingType As Type) As EnumBuilder

Parámetros

name
String

Ruta de acceso completa del tipo de enumeración. name no puede contener valores null insertados.

visibility
TypeAttributes

Atributos de tipo de la enumeración. Los atributos son los bits definidos por VisibilityMask.

underlyingType
Type

Tipo subyacente de la enumeración. Debe ser un tipo entero integrado.

Devoluciones

Enumeración que se ha definido.

Excepciones

Se proporcionan atributos que no son de visibilidad.

o bien

Ya existe una enumeración con el nombre especificado en el ensamblado principal de este módulo.

o bien

Los atributos de visibilidad no coinciden con el ámbito de la enumeración. Por ejemplo, se especifica NestedPublic para visibility pero la enumeración no es un tipo anidado.

name es null.

Ejemplos

En el ejemplo siguiente se muestra el uso de DefineEnum para implementar una clase de enumeración en un módulo dinámico. En el ejemplo se define una enumeración denominada Elevation que tiene un tipo subyacente de Int32y se crean dos elementos: Low, con un valor de 0 y High, con un valor de 1. Una vez creado el tipo, el ensamblado se guarda con el nombre TempAssembly.dll. Puede usar el Ildasm.exe (Desensamblador de IL) para examinar el contenido de este ensamblado.

Nota

Antes de la versión 2.0 de .NET Framework, este ejemplo de código no genera una enumeración correcta.

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;

void main()
{
    // Get the current application domain for the current thread.
    AppDomain^ currentDomain = AppDomain::CurrentDomain;
      
    // Create a dynamic assembly in the current application domain, 
    // and allow it to be executed and saved to disk.
    AssemblyName^ aName = gcnew AssemblyName("TempAssembly");
    AssemblyBuilder^ ab = currentDomain->DefineDynamicAssembly( 
            aName, AssemblyBuilderAccess::RunAndSave);
      
    // Define a dynamic module in "TempAssembly" assembly. For a single-
    // module assembly, the module has the same name as the assembly.
    ModuleBuilder^ mb = 
            ab->DefineDynamicModule(aName->Name, aName->Name + ".dll");
      
    // Define a public enumeration with the name "Elevation" and an 
    // underlying type of Int32.
    EnumBuilder^ eb = 
            mb->DefineEnum("Elevation", TypeAttributes::Public, int::typeid);
      
    // Define two members, "High" and "Low".
    eb->DefineLiteral("Low", (Object^) 0);
    eb->DefineLiteral("High", 1);

    // Create the type and save the assembly.
    Type^ finished = eb->CreateType();
    ab->Save(aName->Name + ".dll");

    for each (Object^ o in Enum::GetValues(finished))
    {
        Console::WriteLine("{0}.{1} = {2}", finished, o, (int)o);
    }
}

/* This code example produces the following output:

Elevation.Low = 0
Elevation.High = 1
 */
using System;
using System.Reflection;
using System.Reflection.Emit;

class Example
{
    public static void Main()
    {
        // Get the current application domain for the current thread.
        AppDomain currentDomain = AppDomain.CurrentDomain;

        // Create a dynamic assembly in the current application domain,
        // and allow it to be executed and saved to disk.
        AssemblyName aName = new AssemblyName("TempAssembly");
        AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(
            aName, AssemblyBuilderAccess.RunAndSave);

        // Define a dynamic module in "TempAssembly" assembly. For a single-
        // module assembly, the module has the same name as the assembly.
        ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

        // Define a public enumeration with the name "Elevation" and an
        // underlying type of Integer.
        EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int));

        // Define two members, "High" and "Low".
        eb.DefineLiteral("Low", 0);
        eb.DefineLiteral("High", 1);

        // Create the type and save the assembly.
        Type finished = eb.CreateType();
        ab.Save(aName.Name + ".dll");

        foreach( object o in Enum.GetValues(finished) )
        {
            Console.WriteLine("{0}.{1} = {2}", finished, o, ((int) o));
        }
    }
}

/* This code example produces the following output:

Elevation.Low = 0
Elevation.High = 1
 */
Imports System.Reflection
Imports System.Reflection.Emit

Module Example
   
    Sub Main()
      
        ' Get the current application domain for the current thread.
        Dim currentDomain As AppDomain = AppDomain.CurrentDomain
      
        ' Create a dynamic assembly in the current application domain, 
        ' and allow it to be executed and saved to disk.
        Dim aName As AssemblyName = New AssemblyName("TempAssembly")
        Dim ab As AssemblyBuilder = currentDomain.DefineDynamicAssembly( _ 
            aName, AssemblyBuilderAccess.RunAndSave)
      
        ' Define a dynamic module in "TempAssembly" assembly. For a single-
        ' module assembly, the module has the same name as the assembly.
        Dim mb As ModuleBuilder = _
            ab.DefineDynamicModule(aName.Name, aName.Name & ".dll")
      
        ' Define a public enumeration with the name "Elevation" and an 
        ' underlying type of Integer.
        Dim eb As EnumBuilder = _
            mb.DefineEnum("Elevation", TypeAttributes.Public, GetType(Integer))
      
        ' Define two members, "High" and "Low".
        eb.DefineLiteral("Low", 0)
        eb.DefineLiteral("High", 1)

        ' Create the type and save the assembly.
        Dim finished As Type = eb.CreateType()
        ab.Save(aName.Name & ".dll")

        For Each o As Object In [Enum].GetValues(finished)
            Console.WriteLine("{0}.{1} = {2}", finished, o, CInt(o))
        Next
   End Sub
End Module

' This code example produces the following output:
'
'Elevation.Low = 0
'Elevation.High = 1

Comentarios

La enumeración definida es una clase derivada de Enum. El value__ campo tiene Private los atributos y SpecialName establecidos.

Para obtener más información sobre los tipos enteros integrados que se pueden especificar como los tipos subyacentes de enumeraciones, vea Información general de la biblioteca de clases.

Nota

En las versiones 1.0 y 1.1 de .NET Framework, es necesario definir enumeraciones mediante TypeBuilder porque EnumBuilder emite enumeraciones cuyos elementos son de tipo Int32 en lugar del tipo de enumeración. En .NET Framework versión 2.0, EnumBuilder emite enumeraciones cuyos elementos tienen el tipo correcto.

Nota

A partir de .NET Framework 2.0 Service Pack 1, este miembro ya no requiere ReflectionPermission con la ReflectionPermissionFlag.ReflectionEmit marca . (Consulte Problemas de seguridad en emisión de reflexión). Para usar esta funcionalidad, la aplicación debe tener como destino .NET Framework 3.5 o posterior.

Se aplica a