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 todos os bits definidos por VisibilityMask.

underlyingType
Type

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

Retornos

A enumeração definida.

Exceções

Atributos diferentes de atributos de visibilidade são fornecidos.

-ou-

Existe uma enumeração com o nome fornecido no assembly pai deste módulo.

-ou-

Os atributos de visibilidade não correspondem ao 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 uma classe de DefineEnum enumeração em um módulo dinâmico. O exemplo define uma enumeração nomeada Elevation que tem um tipo subjacente de Int32, e 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 deste assembly.

Note

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

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 e SpecialName os atributos definidos.

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

Note

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.

Aplica-se a