ModuleBuilder.DefineEnum(String, TypeAttributes, Type) Метод
Определение
Определяет тип перечисления, который является типом значения с одним нестатическим полем, называемым value__
указанного типа.Defines an enumeration type that is a value type with a single non-static field called value__
of the specified type.
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
Параметры
- name
- String
Полный путь к типу перечисления.The full path of the enumeration type. Параметр name
не может содержать внедренные значения NULL.name
cannot contain embedded nulls.
- visibility
- TypeAttributes
Атрибуты типа данного перечисления.The type attributes for the enumeration. Атрибутами являются любые биты, определенные с помощью VisibilityMask.The attributes are any bits defined by VisibilityMask.
- underlyingType
- Type
Базовый тип данного перечисления.The underlying type for the enumeration. Это должен быть встроенный целочисленный тип.This must be a built-in integer type.
Возвращаемое значение
Определенное перечисление.The defined enumeration.
Исключения
Переданы атрибуты, не являющиеся атрибутами видимости.Attributes other than visibility attributes are provided.
-или--or- Перечисление с указанным именем существует в родительской сборке этого модуля.An enumeration with the given name exists in the parent assembly of this module.
-или--or-
Атрибуты видимости не соответствуют области действия перечисления.The visibility attributes do not match the scope of the enumeration. Например, если в качестве значения параметра visibility
указано NestedPublic, но перечисление не относится к вложенному типу.For example, NestedPublic is specified for visibility
, but the enumeration is not a nested type.
name
имеет значение null
.name
is null
.
Примеры
В следующем примере показано использование DefineEnum
для реализации класса перечисления в динамическом модуле.The following example illustrates the use of DefineEnum
to implement an enumeration class in a dynamic module. В примере определяется перечисление с именем Elevation
, имеющим базовый тип Int32 , и создаются два элемента: Low
, со значением 0 и High
значение 1.The example defines an enumeration named Elevation
that has an underlying type of Int32, and creates two elements: Low
, with a value of 0, and High
, with a value of 1. После создания типа сборка сохраняется с именем TempAssembly.dll
.After the type has been created, the assembly is saved with the name TempAssembly.dll
. Для просмотра содержимого этой сборки можно использовать Ildasm.exe (IL) .You can use the Ildasm.exe (IL Disassembler) to examine the contents of this assembly.
Примечание
До версии .NET Framework 2,0 этот пример кода не создает правильное перечисление.Prior to the .NET Framework version 2.0, this code example does not produce a correct enumeration.
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
Комментарии
Определенное перечисление является производным классом класса Enum .The defined enum is a derived class of Enum. Для value__
поля Private SpecialName заданы атрибуты и.The value__
field has Private and SpecialName attributes set.
Дополнительные сведения о встроенных целочисленных типах, которые можно указать в качестве базовых типов перечислений, см. в разделе Общие сведения о библиотеке классов.For more information about the built-in integer types that can be specified as the underlying types of enumerations, see Class Library Overview.
Примечание
В .NET Framework версиях 1,0 и 1,1 необходимо определить перечисления с помощью, TypeBuilder поскольку EnumBuilder выдает перечисления, элементы которых имеют тип, Int32 а не тип перечисления.In the .NET Framework versions 1.0 and 1.1, it is necessary to define enumerations using TypeBuilder because EnumBuilder emits enumerations whose elements are of type Int32 instead of the enumeration type. В .NET Framework версии 2,0 EnumBuilder выдает перечисления, элементы которых имеют правильный тип.In the .NET Framework version 2.0, EnumBuilder emits enumerations whose elements have the correct type.
Примечание
Начиная с .NET Framework 2.0 с пакетом обновления 1 (SP1).NET Framework 2.0 Service Pack 1 , этот член больше не требует наличия ReflectionPermission ReflectionPermissionFlag.ReflectionEmit флага.Starting with the .NET Framework 2.0 с пакетом обновления 1 (SP1).NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (См. раздел вопросы безопасности в порождении отражения.) Чтобы использовать эту функцию, приложение должно быть предназначено для .NET Framework 3,5.NET Framework 3.5 или более поздней версии.(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3,5.NET Framework 3.5 or later.