2010-11-19 8 views
4

Ce scénario n'est pas courant. J'essaie d'invoquer une exception par la réflexion. J'ai quelque chose comme: testMethod est de type MethodBuilderThrowException par réflexion

testMethod.GetILGenerator().ThrowException(typeof(CustomException)); 

Mon CustomException n'a pas de constructeur par défaut, de sorte que les erreurs de déclaration ci-dessus sur un ArgumentException donnant. S'il existe un constructeur par défaut, cela fonctionne correctement.

Alors est-il un moyen, cela peut fonctionner avec aucun constructeur par défaut? Été essayer pendant 2 heures maintenant. :(

Toute aide est appréciée

Merci

Répondre

2

Voir la documentation.!

// This example uses the ThrowException method, which uses the default 
// constructor of the specified exception type to create the exception. If you 
// want to specify your own message, you must use a different constructor; 
// replace the ThrowException method call with code like that shown below, 
// which creates the exception and throws it. 
// 
// Load the message, which is the argument for the constructor, onto the 
// execution stack. Execute Newobj, with the OverflowException constructor 
// that takes a string. This pops the message off the stack, and pushes the 
// new exception onto the stack. The Throw instruction pops the exception off 
// the stack and throws it. 
//adderIL.Emit(OpCodes.Ldstr, "DoAdd does not accept values over 100."); 
//adderIL.Emit(OpCodes.Newobj, _ 
//    overflowType.GetConstructor(new Type[] { typeof(String) })); 
//adderIL.Emit(OpCodes.Throw); 
5

La méthode ThrowException se résume essentiellement à la

suivante
Emit(OpCodes.NewObj, ...); 
Emit(OpCodes.Throw); 

La clé voici pour remplacer le premier Emit appels avec l'ensemble des instructions IL nécessaires pour créer une instance de votre exception personnalisée. Ajoutez ensuite le Emit(OpCodes.Throw)

Par exemple

class MyException : Exception { 
    public MyException(int p1) {} 
} 

var ctor = typeof(MyException).GetConstructor(new Type[] {typeof(int)}); 
var gen = builder.GetILGenerator(); 
gen.Emit(OpCodes.Ldc_I4, 42); 
gen.Emit(OpCodes.NewObj, ctor); 
gen.Emit(OpCodes.Throw); 
Questions connexes