2010-11-19 9 views
4

Dies ist kein allgemeines Szenario. Ich versuche, eine Ausnahme durch Reflexion herbeizuführen. Ich habe so etwas wie: testmethod ist vom Typ MethodThrowException durch Reflexion

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

Meine CustomException keinen Standardkonstruktor hat, so dass die obige Aussage Fehler heraus ein Argument geben. Wenn ein Standardkonstruktor vorhanden ist, funktioniert das problemlos.

Also gibt es einen Weg, kann dies mit keinem Standardkonstruktor arbeiten? Ich habe es jetzt 2 Stunden lang versucht. :(

Jede Hilfe ist willkommen

Dank

Antwort

2

der Siehe 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

Die ThrowException Verfahren im Wesentlichen darauf an folgende

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

Der Schlüssel Hier ist der erstezu ersetzenruft die IL-Anweisungssätze auf, die zum Erstellen einer Instanz Ihrer benutzerdefinierten Ausnahme benötigt werden. Dann fügen Sie die Emit(OpCodes.Throw)

Zum Beispiel

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); 
Verwandte Themen