Cet article a fait l’objet d’une traduction automatique. Pour afficher l’article en anglais, activez la case d’option Anglais. Vous pouvez également afficher le texte anglais dans une fenêtre contextuelle en faisant glisser le pointeur de la souris sur le texte traduit.
Traduction
Anglais

TypeBuilder.CreateType méthode ()

 

Date de publication : novembre 2016

Crée un objet Type pour la classe. Après avoir défini les champs et les méthodes sur la classe, CreateType est appelé pour charger son objet Type.

Espace de noms:   System.Reflection.Emit
Assembly:  mscorlib (dans mscorlib.dll)

public Type CreateType()

Valeur de retour

Type: System.Type

Retourne le nouvel objet Type pour cette classe.

Exception Condition
InvalidOperationException

Le type englobant n’a pas été créé.

ou

Ce type est non abstrait et contient une méthode abstraite.

ou

Ce type n’est pas une classe abstraite ni une interface et contient une méthode sans corps de méthode.

NotSupportedException

Le type contient un code MSIL (Microsoft Intermediate Language) non valide.

ou

La cible de branche est spécifiée à l’aide d’un offset de 1 octet, mais la cible est à une distance supérieure à 127 octets de la branche.

TypeLoadException

Impossible de charger le type. Par exemple, il contient une méthode static avec la convention d’appel HasThis.

If this type is a nested type, the M:System.Reflection.Emit.TypeBuilder.CreateType method must be called on the enclosing type before it is called on the nested type.

If the current type derives from an incomplete type or implements incomplete interfaces, call the M:System.Reflection.Emit.TypeBuilder.CreateType method on the parent type and the interface types before calling it on the current type.

If the enclosing type contains a field that is a value type defined as a nested type (for example, a field that is an enumeration defined as a nested type), calling the M:System.Reflection.Emit.TypeBuilder.CreateType method on the enclosing type will generate a E:System.AppDomain.TypeResolve event. This is because the loader cannot determine the size of the enclosing type until the nested type has been completed. The caller should define a handler for the E:System.AppDomain.TypeResolve event to complete the definition of the nested type by calling M:System.Reflection.Emit.TypeBuilder.CreateType on the T:System.Reflection.Emit.TypeBuilder object that represents the nested type. The code example for this topic shows how to define such an event handler.

A type is created only once, no matter how many times the M:System.Reflection.Emit.TypeBuilder.CreateType method is called. All calls return the same T:System.Type object.

The following code example shows how to define an event handler for the E:System.AppDomain.TypeResolve event, in order to call the M:System.Reflection.Emit.TypeBuilder.CreateType method on a nested type during a M:System.Reflection.Emit.TypeBuilder.CreateType call on the enclosing type.


using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Text;
using System.Resources;
using System.Collections;
using System.IO;

internal class NestedEnum {    
    internal static TypeBuilder enumType = null;
    internal static Type tNested = null;   
    internal static Type tNesting = null;

    public static void Main(String[] args) {
	AssemblyName asmName = new AssemblyName();
	asmName.Name = "NestedEnum";
	AssemblyBuilder asmBuild = Thread.GetDomain().DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
	ModuleBuilder modBuild = asmBuild.DefineDynamicModule("ModuleOne", "NestedEnum.dll");       

	// Hook up the event listening.
	TypeResolveHandler typeResolveHandler = new TypeResolveHandler(modBuild);
	// Add a listener for the type resolve events.
	AppDomain currentDomain = Thread.GetDomain();
	ResolveEventHandler resolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveEvent);
	currentDomain.TypeResolve += resolveHandler;

	TypeBuilder tb = modBuild.DefineType("AType", TypeAttributes.Public);
	TypeBuilder eb = tb.DefineNestedType("AnEnum", TypeAttributes.NestedPublic | TypeAttributes.Sealed, typeof(Enum), null);
	eb.DefineField("value__", typeof(int), FieldAttributes.Private | FieldAttributes.SpecialName);
	FieldBuilder fb = eb.DefineField("Field1", eb, FieldAttributes.Public | FieldAttributes.Literal | FieldAttributes.Static);
	fb.SetConstant(1);

	enumType = eb;

	// Comment out this field.
	// When this field is defined, the loader cannot determine the size
	// of the type. Therefore, a TypeResolve event is generated when the
	// nested type is completed.
	tb.DefineField("Field2", eb, FieldAttributes.Public);        

	tNesting = tb.CreateType();
	if (tNesting == null)
	    Console.WriteLine("NestingType CreateType failed but didn't throw!");	

	try {
	    tNested = eb.CreateType();
	    if (tNested == null)
		Console.WriteLine("NestedType CreateType failed but didn't throw!");	
	}
	catch {
	    // This is needed because you might have already completed the type in the TypeResolve event.
	}

	if (tNested != null) {
	    Type x = tNested.DeclaringType;
	    if (x == null)
		Console.WriteLine("Declaring type was null.");
	    else 
		Console.WriteLine(x.Name);
	}

	asmBuild.Save( "NestedEnum.dll" );

	// Remove the listener for the type resolve events.
	currentDomain.TypeResolve -= resolveHandler;
    }
}

// Helper class called when a resolve type event is raised.
internal class TypeResolveHandler 
{
    private Module m_Module;

    public TypeResolveHandler(Module mod)
    {
	m_Module = mod;
    }

    public Assembly ResolveEvent(Object sender, ResolveEventArgs args)
    {
	Console.WriteLine(args.Name);
	// Use args.Name to look up the type name. In this case, you are getting AnEnum.
	try {
	    NestedEnum.tNested = NestedEnum.enumType.CreateType();
	}
	catch {
	    // This is needed to throw away InvalidOperationException.
	    // Loader might send the TypeResolve event more than once
	    // and the type might be complete already.
	}

	// Complete the type.		    
	return m_Module.Assembly;
    }
}

.NET Framework
Disponible depuis 1.1
Silverlight
Disponible depuis 2.0
Retour au début
Afficher: