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

Definição

Define um tipo de enumeração que é um tipo de valor com um único campo não estático chamado value__ do 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

O caminho completo do tipo de enumeração. name não pode conter nulos inseridos.

visibility
TypeAttributes

Os atributos de tipo para a enumeração. Os atributos são quaisquer bits definidos pelo VisibilityMask.

underlyingType
Type

O tipo subjacente para a enumeração. Isso deve ser um tipo inteiro interno.

Retornos

A enumeração definida.

Exceções

Atributos que não sejam os atributos de visibilidade são fornecidos.

- ou -

Uma enumeração com o nome especificado existe no assembly pai deste módulo.

- ou -

Os atributos de visibilidade não coincidem com o escopo da enumeração. Por exemplo, NestedPublic é especificado para visibility, mas a enumeração não é um tipo aninhado.

name é null.

Exemplos

O exemplo a seguir ilustra o uso de DefineEnum para implementar uma classe de enumeração em um módulo dinâmico. O exemplo define uma enumeração chamada Elevation que tem um tipo subjacente de Int32e cria dois elementos: Low, com um valor de 0 e High, com um valor de 1. Depois que o tipo for criado, o assembly será salvo com o nome TempAssembly.dll. Você pode usar o Ildasm.exe (IL Disassembler) para examinar o conteúdo desse assembly.

Observação

Antes do .NET Framework versão 2.0, este exemplo de código não produz uma enumeração correta.

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

Comentários

A enumeração definida é uma classe derivada de Enum. O value__ campo tem Private atributos e SpecialName definidos.

Para obter mais informações sobre os tipos inteiros internos que podem ser especificados como os tipos subjacentes de enumerações, consulte Visão geral da biblioteca de classes.

Observação

No .NET Framework versões 1.0 e 1.1, é necessário definir enumerações usando TypeBuilder porque EnumBuilder emite enumerações cujos elementos são do tipo Int32 em vez do tipo de enumeração. No .NET Framework versão 2.0, EnumBuilder emite enumerações cujos elementos têm o tipo correto.

Observação

A partir do .NET Framework 2.0 Service Pack 1, esse membro não requer ReflectionPermission mais com o ReflectionPermissionFlag.ReflectionEmit sinalizador . (Consulte Problemas de segurança na emissão de reflexão.) Para usar essa funcionalidade, seu aplicativo deve ter como destino o .NET Framework 3.5 ou posterior.

Aplica-se a