다음을 통해 공유


TypeBuilder.DefineTypeInitializer Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Defines the initializer for this type.

Namespace:  System.Reflection.Emit
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<ComVisibleAttribute(True)> _
<SecuritySafeCriticalAttribute> _
Public Function DefineTypeInitializer As ConstructorBuilder
[ComVisibleAttribute(true)]
[SecuritySafeCriticalAttribute]
public ConstructorBuilder DefineTypeInitializer()

Return Value

Type: System.Reflection.Emit.ConstructorBuilder
A type initializer.

Exceptions

Exception Condition
InvalidOperationException

The containing type has been previously created using CreateType.

Remarks

The created initializer is always public.

Examples

The following example demonstrates how to create an initialization constructor using DefineTypeInitializer.

Imports System.Reflection
Imports System.Reflection.Emit

Public Class Example

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      Dim myAssemblyName As New AssemblyName("EmittedAssembly")
      Dim myAssembly As AssemblyBuilder = _
         AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName, _
                                                               AssemblyBuilderAccess.Run)
      Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule")

      ' Define a public class named "HelloWorld" in the assembly. By default,
      ' this class has a public parameterless instance constructor, so there
      ' is no need to create one.
      Dim helloWorldClass As TypeBuilder = myModule.DefineType("HelloWorld", TypeAttributes.Public)

      ' Define a private Shared String field named "Greeting" in the type.
      Dim greetingField As FieldBuilder = _
         helloWorldClass.DefineField("Greeting", GetType(String), _
                          FieldAttributes.Private Or FieldAttributes.Static)

      ' Create the type initializer (class constructor).
      Dim cctor As ConstructorBuilder = helloWorldClass.DefineTypeInitializer()

      ' Generate IL for the type initializer, which initializes the private 
      ' field.
      Dim il As ILGenerator = cctor.GetILGenerator()

      il.Emit(OpCodes.Ldstr, "Hello, {0}!")
      il.Emit(OpCodes.Stsfld, greetingField)
      il.Emit(OpCodes.Ret)

      ' Create an instance method named Greetings, which takes a string
      ' argument and returns a string.
      Dim greetings As MethodBuilder = _
         helloWorldClass.DefineMethod("Greetings", MethodAttributes.Public, _
                                      GetType(String), New Type() { GetType(String) })

      ' Generate IL for the method, which uses an overload of the String.Format
      ' method to insert the string argument into the string in greetingField.
      ' Thus, any instance of HelloWorld can create formatted greetings as soon
      ' as it is instantiated.
      il = greetings.GetILGenerator()

      il.Emit(OpCodes.Ldsfld, greetingField)
      il.Emit(OpCodes.Ldarg_1)
      il.Emit(OpCodes.Call, GetType(String).GetMethod("Format", _
                                      New Type() { GetType(String), GetType(Object) }))
      il.Emit(OpCodes.Ret)

      ' Create the type and display its constructors. The type initializer is
      ' always named .cctor.
      Dim t As Type = helloWorldClass.CreateType()

      outputBlock.Text &= "Type name: " & t.Name & vbCrLf
      outputBlock.Text &= "Constructors:" & vbCrLf
      For Each ctor As ConstructorInfo In t.GetConstructors(BindingFlags.Public Or _
                   BindingFlags.NonPublic Or BindingFlags.Static Or BindingFlags.Instance)
         outputBlock.Text &= "   " & ctor.ToString() & vbCrLf
      Next 

      ' Create an instance of HelloWorld, and generate a greeting.
      Dim obj As Object = Activator.CreateInstance(t)
      outputBlock.Text &= vbLf & t.InvokeMember("Greetings", _
                                                BindingFlags.InvokeMethod, _
                                                Type.DefaultBinder, _
                                                obj, _
                                                New Object() { "World" }) & vbLf
   End Sub 
End Class 

' This code produces the following output:
'
'Type name: HelloWorld
'Constructors:
'    Void .cctor()
'    Void .ctor()
'
'Hello, World!
using System.Reflection;
using System;
using System.Reflection.Emit;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      AssemblyName myAssemblyName = new AssemblyName("EmittedAssembly");
      AssemblyBuilder myAssembly = 
         AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName, 
                                                       AssemblyBuilderAccess.Run);
      ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");

      // Define a public class named "HelloWorld" in the assembly. By default,
      // this class has a public parameterless instance constructor, so there
      // is no need to create one.
      TypeBuilder helloWorldClass = myModule.DefineType("HelloWorld", TypeAttributes.Public);

      // Define a private Shared String field named "Greeting" in the type.
      FieldBuilder greetingField = 
         helloWorldClass.DefineField("Greeting", typeof(string), 
                                     FieldAttributes.Private | FieldAttributes.Static);

      // Create the type initializer (class constructor).
      ConstructorBuilder cctor = helloWorldClass.DefineTypeInitializer();

      // Generate IL for the type initializer, which initializes the private 
      // field.
      ILGenerator il = cctor.GetILGenerator();

      il.Emit(OpCodes.Ldstr, "Hello, {0}!");
      il.Emit(OpCodes.Stsfld, greetingField);
      il.Emit(OpCodes.Ret);

      // Create an instance method named Greetings, which takes a string
      // argument and returns a string.
      MethodBuilder greetings = 
         helloWorldClass.DefineMethod("Greetings", MethodAttributes.Public, 
                                      typeof(string), new Type[] { typeof(string) });

      // Generate IL for the method, which uses an overload of the String.Format
      // method to insert the string argument into the string in greetingField.
      // Thus, any instance of HelloWorld can create formatted greetings as soon
      // as it is instantiated.
      il = greetings.GetILGenerator();

      il.Emit(OpCodes.Ldsfld, greetingField);
      il.Emit(OpCodes.Ldarg_1);
      il.Emit(OpCodes.Call, typeof(string).GetMethod("Format", 
                             new Type[] { typeof(string), typeof(object) }));
      il.Emit(OpCodes.Ret);

      // Create the type and display its constructors. The type initializer is
      // always named .cctor.
      Type t = helloWorldClass.CreateType();

      outputBlock.Text += "Type name: " + t.Name + "\n";
      outputBlock.Text += "Constructors:\n";
      foreach(ConstructorInfo ctor in t.GetConstructors(BindingFlags.Public | 
                BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
      {
         outputBlock.Text += "   " + ctor.ToString() + "\n";
      }

      // Create an instance of HelloWorld, and generate a greeting.
      object obj = Activator.CreateInstance(t);
      outputBlock.Text += "\n" + t.InvokeMember("Greetings", 
                                                BindingFlags.InvokeMethod, 
                                                Type.DefaultBinder, 
                                                obj, 
                                                new object[] { "World" }) + "\n";
   }
}

/* This code produces the following output:

Type name: HelloWorld
Constructors:
    Void .cctor()
    Void .ctor()

Hello, World!
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.