ModuleBuilder.DefineEnum(String, TypeAttributes, Type) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
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 percurso completo do tipo de enumeração.
name não pode conter nulos embutidos.
- visibility
- TypeAttributes
Os atributos de tipo para a enumeração. Os atributos são quaisquer bits definidos por VisibilityMask.
- underlyingType
- Type
O tipo subjacente para a enumeração. Isto deve ser um tipo inteiro incorporado.
Devoluções
A enumeração definida.
Exceções
São fornecidos atributos para além dos atributos de visibilidade.
-ou-
Existe uma enumeração com o nome próprio na assembleia principal deste módulo.
-ou-
Os atributos de visibilidade não correspondem ao âmbito da enumeração. Por exemplo, NestedPublic é especificado para visibility, mas a enumeração não é um tipo aninhado.
name é null.
Exemplos
O exemplo seguinte ilustra a utilização de DefineEnum para implementar uma classe de enumeração num módulo dinâmico. O exemplo define uma enumeração chamada Elevation que tem um tipo subjacente de Int32, e cria dois elementos: Low, com valor 0, e High, com valor 1. Depois de o tipo ter sido criado, a montagem é guardada com o nome TempAssembly.dll. Pode usar o Ildasm.exe (IL Disassembler) para examinar o conteúdo desta assembleia.
Note
Antes da versão 2.0 do .NET Framework, 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
Observações
O enum definido é uma classe derivada de Enum. O value__ campo tem Private e SpecialName atributos definidos.
Para mais informações sobre os tipos inteiros incorporados que podem ser especificados como os tipos subjacentes de enumerações, consulte Visão Geral da Biblioteca de Classes.
Note
Nas versões 1.0 e 1.1 .NET Framework, é 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. Na versão 2.0 do .NET Framework, EnumBuilder emite enumerações cujos elementos têm o tipo correto.