Lire en anglais

Partager via


TypeBuilder.DefineTypeInitializer Méthode

Définition

Définit l’initialiseur de ce type.

C#
public System.Reflection.Emit.ConstructorBuilder DefineTypeInitializer();
C#
[System.Runtime.InteropServices.ComVisible(true)]
public System.Reflection.Emit.ConstructorBuilder DefineTypeInitializer();

Retours

Retourne un initialiseur de type.

Attributs

Exceptions

Le type conteneur a déjà été créé à l’aide de CreateType().

Exemples

L’exemple de code suivant montre comment créer un constructeur d’initialisation à l’aide de DefineTypeInitializer.

C#
public class MyApplication
{
   public static void Main()
   {
      // Create the "HelloWorld" class
      Type helloWorldType = CreateType();
      Console.WriteLine("Full Name : " + helloWorldType.FullName);
      Console.WriteLine("Static constructors:");
      ConstructorInfo[] info =
         helloWorldType.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic);
      for(int index=0; index < info.Length; index++)
         Console.WriteLine(info[index].ToString());
      
      // Print value stored in the static field
      Console.WriteLine(helloWorldType.GetField("Greeting").GetValue(null)); 
      Activator.CreateInstance(helloWorldType);
   }

   // Create the dynamic type.
   private static Type CreateType()
   {
      AssemblyName myAssemblyName = new AssemblyName();
      myAssemblyName.Name = "EmittedAssembly";

      // Create the callee dynamic assembly.
      AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly(myAssemblyName,
         AssemblyBuilderAccess.Run);
      // Create a dynamic module named "CalleeModule" in the callee assembly.
      ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");

      // Define a public class named "HelloWorld" in the assembly.
      TypeBuilder helloWorldClass = myModule.DefineType("HelloWorld", TypeAttributes.Public);
      // Define a public static string field named "Greeting" in the type.
      FieldBuilder greetingField = helloWorldClass.DefineField("Greeting", typeof(String),
         FieldAttributes.Static | FieldAttributes.Public);

      // Create the static constructor.
      ConstructorBuilder constructor = helloWorldClass.DefineTypeInitializer();

      // Generate IL for the method. 
      // The constructor stores its "Hello emit!" in the public field.
      ILGenerator constructorIL = constructor.GetILGenerator();

      constructorIL.Emit(OpCodes.Ldstr, "Hello emit!");
      constructorIL.Emit(OpCodes.Stsfld, greetingField);      
      constructorIL.Emit(OpCodes.Ret);

      return helloWorldClass.CreateType();
   }
}

Remarques

L’initialiseur créé est toujours public.

S’applique à

Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided), 2.1