EnumBuilder.DefineLiteral(String, Object) Метод

Определение

Определяет именованное статическое поле в типе перечисления с указанным константным значением.

public:
 System::Reflection::Emit::FieldBuilder ^ DefineLiteral(System::String ^ literalName, System::Object ^ literalValue);
public System.Reflection.Emit.FieldBuilder DefineLiteral(string literalName, object? literalValue);
public System.Reflection.Emit.FieldBuilder DefineLiteral(string literalName, object literalValue);
member this.DefineLiteral : string * obj -> System.Reflection.Emit.FieldBuilder
Public Function DefineLiteral (literalName As String, literalValue As Object) As FieldBuilder

Параметры

literalName
String

Имя статического поля.

literalValue
Object

Константное значение литерала.

Возвращаемое значение

Определенное поле.

Примеры

В следующем примере кода показано построение перечисления в динамической сборке с помощью EnumBuilder. В примере определяется перечисление с Elevationбазовым типом Int32и создается два элемента: Lowсо значением 0 и Highзначением 1. После создания типа сборка сохраняется с именем TempAssembly.dll. Для проверки содержимого этой сборки можно использовать Ildasm.exe (IL Disassembler ).

Note

До .NET Framework версии 2.0 этот пример кода не создает правильное перечисление.

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

Комментарии

Определенное поле будет иметь атрибуты PublicStaticполя и Literal задать.

Note

В .NET Framework версии 1.0 и 1.1 необходимо определить перечисления с помощью TypeBuilder, так как EnumBuilder выдает перечисления, элементы которых имеют тип Int32 вместо типа перечисления. В .NET Framework версии 2.0 EnumBuilder выдает перечисления, элементы которых имеют правильный тип.

Применяется к